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.
- Make a new controller for my rogue actions
- Move the actions from the old controller into the new one
- Create a folder for the views
- Moved the views for the actions that were transferred to the new controller.
- 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:
1ink_to :controller => 'foo', :action => 'bar', :id => 'baz'
If you use a named route, the code becomes easier to read, and easier to refactor
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!