【问题标题】:Rails - Helper Singleton and Rails Route Helpers in a PresenterRails - 演示者中的 Helper Singleton 和 Rails Route Helpers
【发布时间】:2012-05-09 13:26:07
【问题描述】:

在我的 Presenter 类中尝试使用路由助手时,我似乎无法弄清楚为什么会出现 500 错误

在下面有一个 Presenter 类 /apps/presenters/base_presenter.rb /apps/presenters/object_presenter.rb

class BasePresenter

  def self.as_collection(collection)
    collection.collect{|object| self.new(object)}
  end

  def help
    Helper.instance
  end

  class Helper
    include Singleton
    include Rails.application.routes.url_helpers
    include ActionView::Helpers::TextHelper
    include ActionView::Helpers::TagHelper
    include ActionView::Helpers::UrlHelper
    include ApplicationHelper
    include UrlHelper
  end

end

所以在我的对象演示器中,我为 as_json 执行以下操作。在我添加此网址之前,一切都有效。不知道为什么它不能访问 Rails 路线。

class ObjectPresenter < BasePresenter


  def initialize( object )
    @object = object
  end

  def as_json(*args)
    { 
        :url => blah_blah_url(@object, :subdomain => "www")
    }
  end

end

任何帮助将不胜感激,因为我很难过 :)

【问题讨论】:

  • 我还注意到,包括 (include ActionView::Helpers::UrlHelper 和 include Rails.application.routes.url_helpers 一起似乎会导致问题

标签: ruby-on-rails ruby-on-rails-3 singleton presenter


【解决方案1】:

好的,我想通了。

class Presenter
  include Rails.application.routes.url_helpers

  def self.as_collection(collection)
    collection.collect{|object| self.new(object)}
  end

  def help
    Helper.instance
  end

  class Helper
    include Singleton
    include ActionView::Helpers::TextHelper
    include ActionView::Helpers::TagHelper
    include ActionView::Helpers::UrlHelper
    include ApplicationHelper
    include UrlHelper
  end

end

然后在我的环境/development.rb中

  Rails.application.routes.default_url_options = { :host => "lvh.me:3000" } # Fixes issue with Presenters not allowing Routes and Url Helper
  config.action_mailer.default_url_options = { :host => "lvh.me:3000" }

还有我的 UrlHelper

module UrlHelper

  def with_subdomain(subdomain)
    subdomain = (subdomain || "")
    subdomain += "." unless subdomain.empty?
    host = Rails.application.routes.default_url_options[:host]
    [subdomain, host].join
  end

  def url_for(options = nil)
    if options.kind_of?(Hash) && options.has_key?(:subdomain)
      options[:host] = with_subdomain(options.delete(:subdomain))
    end
    super
  end

end

【讨论】:

    猜你喜欢
    • 2015-05-04
    • 2013-05-31
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多