我如何将像“root_path”这样的 Rails 路由助手作为 类方法 添加到像 my_model.rb 这样的类中?
所以我的课是这样的:
Class MyModel
def self.foo
return self.root_path
end
end
MyModel.foo
以上不起作用,因为 Class MyModel 不响应 root_path
这是我所知道的:
- 我可以使用 include
Rails.application.routes.url_helpers
,但这只会将模块的方法添加为实例方法 - 我试过扩展
Rails.application.routes.url_helpers
但它没用
请随时给我上课 :)
最佳答案
通常不需要从模型访问 URL 路由。通常,您只需要在处理请求或呈现 View 时(如果您正在格式化链接 URL)从 Controller 访问它们。
因此,无需向模型对象询问根路径,只需从 Controller 或 View 中调用 root_path
。
编辑
如果您只是对无法将模块的方法作为类方法包含在您的类中的原因感兴趣,我不希望简单的 include
起作用,因为它会包含模块的方法作为类中的实例方法。
extend
通常会起作用,但在这种情况下,由于 url_helpers
方法的实现方式,它不会起作用。来自 actionpack/lib/action_dispatch/routing/route_set.rb来源
def url_helpers
@url_helpers ||= begin
routes = self
helpers = Module.new do
...
included do
routes.install_helpers(self)
singleton_class.send(:redefine_method, :_routes) { routes }
end
包含 routes.install_helpers(self)
调用的 included
block 表示您需要include
模块才能获得方法安装(因此 extend
已退出)。
如果您在类上下文中调用 extend
,则以下内容应该有效。试试这个:
Class MyModel
class << self
include Rails.application.routes.url_helpers
end
end
Class.root_path
关于ruby-on-rails - 将 Rails 路由助手作为类方法添加到类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17815950/