Trey Connell

March 23, 2010 | In: Ruby on Rails

Use Rails’ RESTful Helpers in Rake Tasks

We were recently working on a rake task to generate an XML Sitemap of a site’s content for submission to the search engines. Because we are trying to remain as RESTful as possible, I wanted to take advantage of the helpers given to me automatically. For example, to generate the URL for an article, I simply have to do article_url(my_article). This would result in something like /articles/my-article-headline-is-cheesy.

I couldn’t figure out for the life of me how to make Rake aware of my routing and the RESTful helpers that I SHOULD be able to use to dry up my code and ensure very little manual maintenance when and if we decided to change our routing in the future. There had to be a way!

It turns out there indeed exists a way to make this happen.  You simply have to place “include ActionController::UrlWriter” at the top of your rake task.  Ultimately url_for is called when you do something like article_url(my_article), and url_for requires a host which it won’t have.  So change your code to read article_url(a, :host => “www.mysite.com”). Voila – route helpers inside your rake task.

1 Response to Use Rails’ RESTful Helpers in Rake Tasks

Avatar

Jan

June 29th, 2010 at 10:18 am

Trey,

I came over the same problem some minutes ago. Great timesaver, so thx for that. But question, why do you put the host into url_helper?

I’d suggest to use Ryan Bates “APP_CONFIG” approach so that your xml generator should look like:

xml.loc(APP_CONFIG[:domain] + article_path(article))

No matter if you are in development, test or production the right domain is used.

Regards
Jan

Comment Form

Tradeomics

Twitterings

Recent Comments

Buy Awesome T-Shirts!

I hate pants t-shirt