concerned_with readable rails models

February 22, 2010

Several models within our web app, Realized-app, have grown to more than 500 lines. Rapidly grasping the relationships among methods in these models had become difficult. Some means of dividing the models into coherent pieces was needed.

An elegant fix came about while reading the code for the rails-based forum, altered_beast. First, app/models contains a 'user' directory. Near the top of models/user.rb, also note a call to concerned_with:

class User < ActiveRecord::Base
  concerned_with :validation, :states, :activation, :posting
  . . .

One of the rails initializers defines concerned_with. Four files named by the symbols passed to concerned_with reside in app/models/user. The user methods pertaining to validation are found in models/user/validation.rb. Without the separation provided by concerned_with, this validation logic would exist in models/user.rb.

Using concerned_with, we have refactored the largest models in Realized-app. Now, at a glance, most of the functionality unique to a particular model becomes readily apparent.

For a good perspective on the origin of concerned_with and how to use it, see this post by Paul Barry.