【问题标题】:Add rails route helpers to a class as class methods将 Rails 路由助手作为类方法添加到类
【发布时间】:2013-07-22 20:42:33
【问题描述】:

如何将诸如“root_path”之类的 Rails 路由助手添加到诸如 my_model.rb 之类的类中作为类方法

所以我的课是这样的:

Class MyModel

  def self.foo
    return self.root_path
  end

end

MyModel.foo

上述方法不起作用,因为 MyModel 类没有响应 root_path

这是我所知道的:

  1. 我可以使用 include Rails.application.routes.url_helpers,但这只会将模块的方法添加为实例方法
  2. 我尝试扩展 Rails.application.routes.url_helpers,但它没有用

请随时给我上学:)

【问题讨论】:

  • 这是使用 MVC 的错误方法。您应该在应用的控制器或助手级别添加与路由相关的方法。
  • 它是如何复制的。他们将其添加为实例方法。我想将它添加为类方法。这就是我的问题:如何将模块实例方法添加为类方法

标签: ruby-on-rails ruby routes


【解决方案1】:

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

因此,无需向模型对象询问根路径,您只需从控制器或视图中调用 root_path

编辑

如果您只是对无法将模块的方法作为类方法包含在类中的原因感兴趣,我不希望简单的include 可以工作,因为这将包含模块的方法instance 类中的方法。

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 块表明您需要include 模块才能安装方法(因此extend 已退出)。

如果您在类上下文中调用extend,以下应该可以工作。试试这个:

Class MyModel
  class << self
    include Rails.application.routes.url_helpers
  end
end
Class.root_path

【讨论】:

  • 我明白你的意思,但这不是我的问题。我在问如何将模块的实例方法添加为类方法。我知道做扩展应该有效,但在我提到的情况下它不起作用。你知道为什么吗?
  • @user566245 明白了。我已经更新了我的答案,请再看一下
  • @user566245 这对你有用吗?请试一试,如果成功,请点赞/接受答案,谢谢!
猜你喜欢
  • 2019-01-24
  • 2012-07-16
  • 1970-01-01
  • 1970-01-01
  • 2019-08-21
  • 2011-04-19
  • 2015-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多