How to access URL helper from rails module How to access URL helper from rails module ruby ruby

How to access URL helper from rails module


In your module, just perform a :

 include Rails.application.routes.url_helpers


Here is how I do it in any context without include

routes = Rails.application.routes.url_helpersurl = routes.some_path

That works in any context. If you're trying to include url_helpers - make sure you are doing that in the right place e.g. this works

module Contact  class << self    include Rails.application.routes.url_helpers  endend

and this does not work

module Contact  include Rails.application.routes.url_helpers  class << self  endend

One more example with Capybara tests

feature 'bla-bla' do  include Rails.application.routes.url_helpers  path = some_path #unknown local variable some_pathend

and now the right one

include Rails.application.routes.url_helpersfeature 'bla-bla' do  path = some_path #this is okend


Delegation to url_helpers seems much better than including the whole module into your model

delegate :url_helpers, to: 'Rails.application.routes' url_helpers.users_url  => 'www.foo.com/users'

reference