2012-04-29 5 views
2

でヘルパーシングルトンとRailsのルートヘルパー私は私のプレゼンタークラスでルートヘルパーを利用しようとしているRailsの - プレゼンター

は、下のプレゼンターのクラスを持っているとき、私は500エラーを得ている理由を見つけ出すように見えることはできません

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 

/apps/presenters/base_presenter.rb /apps/presenters/object_presenter.rbはので、私のオブジェクトのプレゼンターに私はas_jsonのために次の操作を行います。私はこのURLを追加するまで、すべてのことが働きます。 Railsのルートにアクセスできない理由に悩まされました。

class ObjectPresenter < BasePresenter 


    def initialize(object) 
    @object = object 
    end 

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

end 

私は困惑していますので、任意の助けもいただければ幸いです:)

+0

私も含めて(ActionView ::ヘルパー:: UrlHelperを含めるとRailsが含まれていることに気づきました。一緒にapplication.routes.url_helpers問題を引き起こすようです – bokor

答えて

4

OK、私はそれを考え出しました。私の環境/ 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で、その後

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 

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 
関連する問題