5

How can i add rails route helpers like "root_path" to a class like my_model.rb as a class method?

So my class is like this:

Class MyModel

  def self.foo
    return self.root_path
  end

end

MyModel.foo

The above doesn't work because Class MyModel doesn't respond to root_path

This is what I know:

  1. I can use include Rails.application.routes.url_helpers, but that only add the module's methods as instance methods
  2. I tried doing extend Rails.application.routes.url_helpers but it didn't work

Please feel free to school me :)

4

1 回答 1

15

通常不需要从模型访问 URL 路由。通常,您只需要在处理请求或呈现视图时从控制器访问它们(例如,如果您正在格式化链接 URL)。

因此,无需向模型对象询问根路径,您只需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

included包含调用的块routes.install_helpers(self)表明您将需要include该模块才能安装方法(因此extend已退出)。

extend如果您在类上下文中调用,则以下内容应该有效。尝试这个:

Class MyModel
  class << self
    include Rails.application.routes.url_helpers
  end
end
Class.root_path
于 2013-07-23T16:45:24.653 回答