How to access URL helper from rails module

I have a module with a function. It resides in /lib/contact.rb:

module Contact
  class << self
    def run(current_user)
      ...
    end
  end
end

I want to access the URL helpers like 'users_path' inside the module. How do I do that?


Solution 1:

In your module, just perform a :

 include Rails.application.routes.url_helpers

Solution 2:

Here is how I do it in any context without include

routes = Rails.application.routes.url_helpers
url = 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
  end
end

and this does not work

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

One more example with Capybara tests

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

and now the right one

include Rails.application.routes.url_helpers
feature 'bla-bla' do
  path = some_path #this is ok
end

Solution 3:

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