What not to do with before_filter ... or around or after filters

03/04/09

I actually saw this code today


before_filter :find_movie, :except => [:match_detail, 
  :auto_complete_for_title, :match_it_search, :search, 
  :compare]

… except that there were four additional actions included in the exception array.

Pretty obvious that they aren’t using REST. I guess I haven’t ranted about REST yet, so here it goes: Do RESTful development.

1. It makes for more maintainable code because you don’t have to look through oodles and oodles of spaghetti actions, usually in unrelated controllers.
2. If you build your REST controllers right, you also get custom APIs, for free. Unless you enjoy writing APIs this is really good.
3. If you extract your non-REST actions into their own RESTful controllers, you have a better grasp of your app. You are fleshing out the concepts that govern and therefore can grow you app without even more spaghetti. Generally if you are using non-REST controllers, you don’t understand your own app landscape.

But, alas, my real rant of the day is about using before filters to avoid calling methods inside the action. Extracting common code is good! Keep creating methods for those things that occur more than once.

On the other hand you don’t gain much from hiding a method call in before_filter. It makes for really bad maintenance when you look in your action and can’t figure out how an instance variable is being set. Then you look at the filters and see a list included and excepted actions using both before_filter and skip_before_filter. That would be the definition of spaghetti code.

Contrary to seemingly popular belief, hiding a method call in the filter isn’t skinnying the action, it is fattening the controller head. Controllers don’t need fat heads.