在我的 Rails 应用程序中的普通旧 Ruby 对象 (PORO) 中:我有以下方法:
def some_method
content_tag(:li, link_to("Do something", somewhere_path(object.id)))
end
首先:对象不理解方法 content_tag
,所以我添加了以下内容,使对象理解该方法:
include ActionView::Helpers::TagHelper
然后对象不理解 link_to
所以我添加了以下内容使对象理解该方法:
include ActionView::Helpers::UrlHelper
现在,它不理解我的路线:somewhere_path(object.id)
。
问题:如何让我的 Rails 应用程序中的 PORO 理解生成路线的助手?
后续问题:是否有更简单的方法将所有这些功能包含到我的 PORO 对象中?也许有一种方法可以只包含
一个主要模块并获得所有这些功能(而不是可能需要 3 个不同的模块)。
最佳答案
您要么必须执行您在 self 回答(链接到 revision I refer to )中描述的操作,要么将一些上下文注入(inject)您的 PORO。上下文是知道所有这些方法的地方。像这样:
class ProjectsController
def update
project = Project.find(params[:id])
presenter = Presenters::Project.new(project, context: view_context) # your PORO
# do something with presenter
end
end
你的 PORO 看起来像这样:
module Presenters
class Project
attr_reader :presentable, :context
def initialize(presentable, context:)
@presentable = presentable
@context = context
end
def special_link
context.somewhere_path(presentable)
end
end
end
我,我两个都不喜欢。但有时我们不得不选择一个较小的邪恶。
If anyone happens to know of a current way to get access to all of these methods with one include statement then let me know.
为什么,是的。有办法。
module MyViewCompatibilityPack
include ActionView::Helpers::TagHelper
include ActionView::Helpers::UrlHelper
def url_helpers
Rails.application.routes.url_helpers
end
end
class MyPoro
include MyViewCompatibilityPack
...
end
关于ruby-on-rails - rails : Make Route Helper Methods Available to PORO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43355582/