我有一个具有功能的模块。它位于 /lib/contact.rb:
module Contact
class << self
def run(current_user)
...
end
end
end
我想访问模块内的 URL 帮助程序,例如“users_path”。我该怎么做?
在您的模块中,只需执行:
include Rails.application.routes.url_helpers
这是我在没有
include
的情况下如何执行此操作的方法
routes = Rails.application.routes.url_helpers
url = routes.some_path
这在任何情况下都有效。如果您尝试
include
url_helpers - 确保您在正确的位置执行此操作,例如这有效
module Contact
class << self
include Rails.application.routes.url_helpers
end
end
这不起作用
module Contact
include Rails.application.routes.url_helpers
class << self
end
end
再一个水豚测试的例子
feature 'bla-bla' do
include Rails.application.routes.url_helpers
path = some_path #unknown local variable some_path
end
现在是正确的
include Rails.application.routes.url_helpers
feature 'bla-bla' do
path = some_path #this is ok
end
委托给 url_helpers 似乎比将整个模块包含到模型中好得多
delegate :url_helpers, to: 'Rails.application.routes'
url_helpers.users_url => 'www.foo.com/users'
我一直在努力解决助手期望从默认控制器和堆栈(
default_url_options
等)获得的细节,并且不想对主机进行硬编码。
当然,我们的 URL 助手是由我们的漂亮模块提供的:
include Rails.application.routes.url_helpers
但按原样包含此内容,并且 (1) 助手将查找
default_url_options
,并且 (2) 不会了解请求主机或请求。
主机部分来自控制器实例的
url_options
。因此,我将控制器上下文传递到我以前的模块中,现在是一个类:
class ApplicationController
def do_nifty_things
HasAccessToRoutes.new(self).render
end
end
class HasAccessToRoutes
include Rails.application.routes.url_helpers
delegate :default_url_options, :url_options, to: :@context
def initialize(context)
@context = context
end
def render
nifty_things_url
end
end
可能并不适合所有情况,但在实现某种自定义渲染器时它对我很有用。
无论如何:
delegate :url_helpers, to: 'Rails.application.routes'
url_helpers.users_url => 'www.foo.com/users'
Augustin Riedinger,该委托代码需要引用 url_helpers (复数),否则你会得到
未定义的方法`url_helper'
我认为值得在单独的答案中提及上面Joshua Pinter的评论。
对于单次使用,简单的内联使用,例如
Rails.application.routes.url_helpers.something_path
似乎是个好方法。