Rails named routes make refactoring a cinch

I have some code that needed to be refactored. I had a controller with actions that should have been somewhere else. Here’s how the refactoring went.

  1. Make a new controller for my rogue actions
  2. Move the actions from the old controller into the new one
  3. Create a folder for the views
  4. Moved the views for the actions that were transferred to the new controller.
  5. Change two named routes in my routes.rb file to use the new controller.

The key part here is the way Rails’ Named Routes make this so easy. Not a line of view code was changed.

Almost all examples of URLs in Rails code I’ve seen use regular routes, but this makes for hard to read code:

routes.rb
map.connect ':controller/:action/:id'
view
link_to :controller => 'foo', :action => 'bar', :id => 'baz'

If you use a named route, the code becomes easier to read, and easier to refactor

routes.rb
map.edit_page 'page/edit/:id',
              :controller => 'page',
              :action => 'edit'
view
link_to edit_page_url(:id => 'baz')

I can now change where the edit_page_url controller and action are without changing all the functionality that uses them. In addition, my view code is a lot more readable.

I may have too many named routes in my code, but I find it easier to have a larger number of more specific routes than a smaller number of generic routes that I can’t get my head around!

This entry was posted on Sat, 21 Jan 2006 08:10:00 GMT . You can follow any any response to this entry through the Atom feed. You can leave a comment or a trackback from your own site.
Tags


Trackbacks

Use the following link to trackback from your own site:
http://blog.craz8.com/trackbacks?article_id=rails-named-routes-make-refactoring-a-cinch&day=21&month=01&year=2006

Comments

Leave a response

Leave a comment