My most recent project at work has been developing a Ruby on Rails application – the same one I started a long time ago. The project was on hiatus for a number of months because of higher priorities, but now at the top of my list again. Since I last touched the code, wants and needs have changed, as they always do, so I’m taking the opportunity to do a complete rewrite of the application. Until I go started, I didn’t realize how bad it was needed.
I didn’t know it until recently, but my code was really a mess. There was too much of it, and when that happens, things break more easily and its harder to track down problems. While listening to a podcast interview with David Heinemeier Hansson, creator of Rails, he made a few comments about good RoR programming practices. One of them was regarding the controller component of the Model/View/Controller layers. He said that he knew things could be improved or simplified if he had more than four or five lines of code in a controller action (don’t worry if you don’t know what that means). In version one of my project, I had one action that was 58 lines long with its controller nearly 600. I obviously had a lot of room for improvement.
This time around, armed with the wisdom of a Rails legend, I’m doing much better. I’m refactoring my code and taking advantage of many of the new features that will be available in the upcoming version 1.2 of Rails. It’s easily at least a 10x improvement over what I wrote previously, and probably a 100x easier to read.
My methodology matched up very closely with that laid out by Jamis Buck (of 37signals) in a blog post from today called Skinny Controller, Fat Model. It’s a great read, packed with a lot of best practices learned through a lot of practice. It’s helped to clarify my thinking a bit more too, for which I’m grateful.
I’m constantly referencing three books during this project besides the numerous websites I’m referencing. They are:
- Edition 2 of Agile Web Development with Rails: A Pragmatic Guide (Pragmatic Programmers)
- Rails Recipes (Pragmatic Programmers)
- Ruby for Rails: Ruby Techniques for Rails Developers
These are all awesome resources for anyone developing in Ruby and Rails, and will save you tons of time and frustration. Buy all three!
If you’re thinking about learning how to program, I recommend a series of tutorials by Chris Pine called Learn to Program that will gently introduce to you to Ruby. It’s also available in good, old fashioned paper too.