Using Rails URL helpers outside of views and controllers

In rails, all URLs are generated through URL helpers, be they named routes like articles_url or explicit routes like url_for(:controller=>'articles', :action => 'index'). Occasionally you’ll find yourself in the position to need to generate a URL outside of a controller or view. First, it’s important to be sure that this isn’t being done to circumvent MVC, and to try and find a way to do this in a view. I encountered this recently when making a sitemap generation script.

The key is to include ActionController::UrlWriter for Rails 2, or Rails.application.routes.url_helpers for Rails 3 in the class you would like to use, which will bring the url_for, *_url, and *_path helpers into that class.

The one gotcha to this is that URL methods with the full will fail unless :host is specified in the arguments. This could be solved by setting the @@default_url_options class attribute.

class UrlGenerator
  include ActionController::UrlWriter #for rails 2
  #Rails.application.routes.url_helpers # for rails 3
  @@default_url_options = {:host => ''}

# from elsewhere
url_generator =