Not Only… But Also¶ ↑
The Rails ‘fat model’ pattern is a good one but can result in very large model classes. It can be unwieldy to work in such files as they begin to look a bit messy. Assuming you have judiciously appraised the model for opportunities to extract out pieces into libraries, it still may leave you with a lot of code. I find this is particularly the case for validations for models with a large number of columns.
This is where allowing for multiple files to define a class can help and is what NotOnlyButAlso does. It defines a convention to help organise multiple files as well as avoiding the need for repititive code when using modules as containers or re-opening the classes.
You might recognise this style of solution as used by the concerned_with plugin (github.com/jakehow/concerned_with/). I wrote this a long time ago before I knew of the concerned_with plugin. I have released it because its got a simpler interface and I love the name.
For interest here are some discussions of this type of solution in regards to concerned_with:
m.onkey.org/2008/9/15/active-record-tips-and-tricks
paulbarry.com/articles/2008/08/30/concerned-with-skinny-controller-skinny-model
For extra credit:
en.wikipedia.org/wiki/Not_Only…_But_Also
Install¶ ↑
From Gemcutter:
gem install not_only_but_also
Or as plugin:
./script/install plugin git://github.com/adzap/not_only_but_also.git
Usage¶ ↑
For example you want to extract out the validations to a separate file:
class Post not_only_but_also :validations end # in app/models/post/validations.rb Post.not_only_but_also do validates_presence_of :title end
OR the shorthand version:
class Post also_has :validations end # in app/models/post/validations.rb Post.also_has do validates_presence_of :title end
There is a generator for quickly creating the context file and the directory if need be
./script/generate not_only_but_also Post validations
Adding the context to the model to have it loaded is left for as an exercise for the developer.
Copyright © 2009 Adam Meehan, released under the MIT license