Concerns is a simple Rails plugin that provides you with a simple way to organise your Controllers, Models and Mailers, and split them into smaller chunks of logic. It is especially useful when you have lengthly models, and get fed up with having to scroll through several hundred lines of code.
How does it work?
So let's say we have a Post model (doesn't everyone?!) which is getting a bit lengthy, and frankly not very nice to look at. With the Concerns plugin, we can split it up into nice little chunks. Because we have lots of validations, let's start by pulling them out and placing them within a concern file.
Let's get going then...
First of all, install the plugin:
script/plugin install git://codaset.com/joelmoss/rails-concerns.git
Then, create a new directory in your app/models drectory and call it "post", which is the same name as your model.
Within this new directory, create a new file at app/models/post/validations.rb. Now all this should do is reopen your Post model, and define your validations like this:
class Post < ActiveRecord::Base
validates_presence_of :title, :body
validates_uniqueness_of :title, :scope => :project_id, :case_sensitive => false
validates_exclusion_of :title, :in => %w(edit new blog delete destroy create update post posts)
validates_inclusion_of :markup_language, :in => %w( markdown textile wikitext ), :allow_nil => true
end
It's just like writing your model again.
Now within your main Post model; right at the top, we simply call:
concerned_with :validations
Multiple concerns can be called like so:
concerned_with :validations, :class_methods
And we're done!
You can do this as many times as you wish, and with as many concerns as you want. And it works with models, controllers and mailers. Need help?
Grab and/or fork the code from the Codaset project
