2

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

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

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

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

4

1 回答 1

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
于 2012-04-30T15:34:42.557 回答