Rails - Helper Singleton和Rails在演示者中路由助手

时间:2012-04-29 16:07:28

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

我似乎无法弄清楚为什么我在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

任何帮助都会非常感激,因为我很难过:)

1 个答案:

答案 0 :(得分:6)

好吧我明白了。

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