Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Named Routes in Rakefile

I have some named routes like this rake routes:

birthdays GET    /birthdays(.:format)                             birthdays#index

In a rakefile I simply want to be able to call birthdays_url like I would in my view.

task :import_birthdays => :environment do
  url = birthdays_url
end

But I'm getting an error undefined local variable or method 'birthdays_url' for main:Object

like image 772
Dex Avatar asked Jul 23 '13 00:07

Dex


People also ask

How do I see all routes in Rails?

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.

How do routes work in Ruby on Rails?

Rails routing is a two-way piece of machinery – rather as if you could turn trees into paper, and then turn paper back into trees. Specifically, it both connects incoming HTTP requests to the code in your application's controllers, and helps you generate URLs without having to hard-code them as strings.


3 Answers

You can either use this example code in your rake task:

include Rails.application.routes.url_helpers
puts birthdays_url(:host => 'example.com')

or you can use this example code in your rake task:

puts Rails.application.routes.url_helpers.birthdays_url(:host => 'example.com')

If you only want the path part of the URL, you can use (:only_path => true) instead of (:host => 'example.com'). So, that would give you just /birthdays instead of http://example.com/birthdays.

You need either the (:host => 'example.com') or (:only_path => true) piece, because the rake task doesn't know that bit of information and will give this error without it:

Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true
like image 162
James Chevalier Avatar answered Oct 19 '22 10:10

James Chevalier


for Rails 4 include code with your domain at the top of your rake task

include Rails.application.routes.url_helpers
default_url_options[:host] = 'example.com'
like image 44
Brian Sigafoos Avatar answered Oct 19 '22 08:10

Brian Sigafoos


use this:

Rails.application.routes.url_helpers.birthdays_url

or to be less verbose:

include Rails.application.routes.url_helpers
url = birthdays_url
like image 3
Benj Avatar answered Oct 19 '22 08:10

Benj