11

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

Dex
  • 12,527
  • 15
  • 69
  • 90

3 Answers3

23

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
James Chevalier
  • 10,604
  • 5
  • 48
  • 74
  • 1
    I don't like hard coding the host. so I use `host: YOUR-APP-NAME::Application.config.action_mailer.default_url_options[:host]` That way it picks it up from your config files. – user2726983 Aug 13 '16 at 12:03
4

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'
Brian Sigafoos
  • 503
  • 6
  • 14
3

use this:

Rails.application.routes.url_helpers.birthdays_url

or to be less verbose:

include Rails.application.routes.url_helpers
url = birthdays_url
Dex
  • 12,527
  • 15
  • 69
  • 90
Benjamin Bouchet
  • 12,971
  • 2
  • 41
  • 73