Rails named routes make refactoring a cinch

January 21, 2006 Link to post  Permalink

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:


1ap.connect ':controller/:action/:id'

1ap.connect :controller/:action/:id


1ink_to :controller => 'foo', :action => 'bar', :id => 'baz'

1ink_to :controller => foo, :action => bar, :id => baz

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


1ap.edit_page 'page/edit/:id',
2              :controller => 'page',
3              :action => 'edit'

1ap.edit_page page/edit/:id,
2 :controller => page,
3 :action => edit


1ink_to edit_page_url(:id => 'baz')

1ink_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!