Skip to content

Instantly share code, notes, and snippets.

@Dacello
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dacello/78d67f649372294872be to your computer and use it in GitHub Desktop.
Save Dacello/78d67f649372294872be to your computer and use it in GitHub Desktop.
layout author title
post
daniel andrews
Skinny Everything (Part 2 of 3)

The first article in this series brought up the following fact about MVC frameworks: while it is very important to have a skinny controller, it is much better to have a skinny everything. If you didnt read the previous article, know that I am talking about Rails specifically, but this concept applies to MVC in general.

The first method I wrote about was using Draper for Decorators, which is a nice way to keep display logic out of models without resorting to using helpers. This article will cover another method for getting skinnier:

##Concerns

Concerns are modules you can use to extract code out of models and controllers. This is useful for various reasons. An obvious one is that this makes things skinnier, which we've already established is good. Another is that you can use these concerns to mix into other models and controllers, which can be especially useful when you have two different models that need to have some similar functionality.

When you start to notice that a model is getting too fat, check to see if it has a bunch of methods that are all related to one feature, responsibility, or "concern." If so, it might be a good idea to break all of those closely related methods into one concern file, which you then include right at the top of the model. Then if something goes wrong with that particular functionality, it will be easier to locate the problem. An Example:

You've got yourself a Product model. Its pretty sweet, except that its starting to get a little fat. Turns out, about 200 lines of the model are related to search methods. So, you decide to move all of the search related methods into a "ProductSearch" concern. Now the model is nice and clean, and you know exactly where to find all of the methods related to the search functionality. Down the line, however, it will most likely be necessary to go one step further; tweak the methods so it is a reusable concern, and call it "Searchable". Then include the searchable concern at the beginning of any model that you want to have that functionality.

Check out this great article by DHH: Put chubby models on a diet with concerns:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment