Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 919
sizzle Avatar asked May 20 '11 16:05

sizzle


People also ask

What are URL Helpers rails?

Module ActionView::Helpers::UrlHelper. Provides a set of methods for making links and getting URLs that depend on the routing subsystem (see ActionDispatch::Routing). This allows you to use the same format for links in views and controllers.

How do I see routes in Rails?

Decoding the http request TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.


2 Answers

In your module, just perform a :

 include Rails.application.routes.url_helpers 
like image 70
ronnieonrails Avatar answered Oct 06 '22 00:10

ronnieonrails


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 
like image 25
Anton Chikin Avatar answered Oct 05 '22 22:10

Anton Chikin