These days it seems to be conventional wisdom to build "skinny" controllers in your Rails app. Skinny controllers help you to consolidate your business logic into one place (the model) which allows for easier maintenance and testing. If you're still not convinced, perhaps you should watch this informative public service announcement.

I've been using the excellent resource_controller plugin by James Golick for well over a year now. Its an excellent tool for handling the standard RESTful controller actions that one normally codes by hand (or generator.) We currently use it in the Spree project and yesterday I was curious to compare the size of these controllers to those of a project that does not use resource_controller. First lets look at the results of running "rake stats" on the Spree project.

spree-stats

As you can see, there are 44 controllers in this project. Yeah, that's a lot of controllers but Spree is a pretty huge project (its a full featured e-commerce platform.) Now notice that out of 44 classes we only have 111 methods. That's an average (rounding down) of only 2 methods per class! The methods themselves are also pretty skinny with an average of 8 lines of code per method.

Now lets take a look at Fat Free CRM. I chose this project because it is similar to Spree in that its a full featured platform (not just a little plugin.) DISCLAIMER: I've never used this application but I've heard good things about it. I'm in no way trying to disparage another person's work here - I just need a point of comparison.

fat-free-stats

You can see that this project's controllers are pretty fat. There are only 12 of them but they have more lines of code then in the 44 controllers of Spree. There are 11 methods per controller (compared to 2 in Spree), with the typical method size being the same as Spree. Don't let the equivalent method size fool you. For instance, take a look at this typical 4 line method in a Spree controller.


create do
  flash nil 
  wants.html {redirect_to edit_order_url(@order)}
end

This is an example of how we override the default resource_controller behavior. In this specific case we did not want to include anything in the flash, nor redirect to show after object creation. If you're happy with the resource_controller defaults, this method is not even needed.

If you're interested in a thorough overview of resource_controller, Fabio Akita has produced a very detailed screencast on how it works. Its one of the longest screencasts I've ever seen (about 1 hr) but its well worth the time if you're struggling to wrap your head around how REST works in Rails (both with and without resource_controller.)

blog comments powered by Disqus