Tuesday, January 13, 2009

Adding Custom Routes for Radiant Projects

While integrating simple_captcha into the guestbook extension of radiant, I had to add a special route for the simple_captcha to work properly.

Unfortunately, the routes file of a radiant project does nothing but loading the routes file from radiant gem itself:

load File.join(RADIANT_ROOT, "config", "routes.rb")

Calling ActionController::Routing::Routes.draw again will clear all the routes that have been defined in the gem routes file. So you have to either modify the code of the gem, or copy the code from routes.rb of the gem radiant to the projects route file.

Or you can append your new routes using add_named_route instead of draw. And since the simple captcha route is supposed to be defined before radiant routes. you can manipulate the routes array as in the last line of the following sample.

load File.join(RADIANT_ROOT, "config", "routes.rb")

       :controller => 'simple_captcha')


add_route is another method similar to add_named_route but doesn't require a name parameter. It also can be used. Note that both aren't documented well in the rails api documentation.

The Previous add_named_route call is equivalent to map.simple_captcha '/simple_captcha/:action', :controller => 'simple_captcha' at the end of the routing block that is passed to draw.
add_route('/path', {options}) is equivalent to map.connect '/path' , {options}.
They can be very usable sometimes.