Rails - 演示者中的 Helper Singleton 和 Rails Route Helpers

Posted

技术标签:

【中文标题】Rails - 演示者中的 Helper Singleton 和 Rails Route Helpers【英文标题】:Rails - Helper Singleton and Rails Route Helpers in a Presenter 【发布时间】: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 一起似乎会导致问题 【参考方案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

【讨论】:

以上是关于Rails - 演示者中的 Helper Singleton 和 Rails Route Helpers的主要内容,如果未能解决你的问题,请参考以下文章

如何在演示者中使用 Enumerable mixin?

php 404在演示者中

Android MVP - 应该避免在演示者中使用 R.string 引用吗?

ruby Rails Test Helper rails_helper.rb

ruby Pluralize Rails Helper

Rails 5 - application_helper.rb 中定义的渲染数组