Memo #6: Using named routes and url_for outside the controller in Ruby on Rails

Posted by Dmytro Shteflyuk on under Ruby & Rails

Sometimes we need to write small console scripts which do some background processing on our models. In Scribd we are using Loops to run these tasks (check Alexey Kovyrin’s introduction post). One of our scripts supposed to generate some sort of html reports, and we need to generate links to our site there.

In Ruby on Rails we are using routes to generate any sort of links. So let’s include routing mechanism into our own script or class.

First, you need to ensure that Rails core is loaded (if you haven’t done this earlier; for example, in script/console you should not do this). I’m assuming you’re creating a script under /script folder:

1
2
3
ENV['RAILS_ENV'] ||= 'production'
require File.dirname(__FILE__) + '/../config/boot'
require RAILS_ROOT + '/config/environment'

Now you need to include ActionController::UrlWriter module, which allows to write URLs from arbitrary places in your codebase, and configure default_url_options[:host]:

5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# this is slow because all routes and resources being calculated now
include ActionController::UrlWriter
default_url_options[:host] = 'www.example.com'

# map.connect ':controller/:action/:id'
url_for(:controller => 'folders', :action => 'show', :id => Folder.first)
# => "http://www.example.com/folders/2"

# map.resources :folders
folders_url
# => "http://www.example.com/folders"
folder_url(Folder.first)
# => "http://www.example.com/folders/2"
edit_folder_url(Folder.first)
# => "http://www.example.com/folders/2/edit"

# you can use relative paths too
folders_path
# => "/folders"

Easy and helpful technique. Enjoy!

No Responses to this entry

Subscribe to comments with RSS

Comments are closed

Comments for this entry are closed for a while. If you have anything to say – use a contact form. Thank you for your patience.