Every repository with this icon (
Every repository with this icon (
| name | age | message | |
|---|---|---|---|
| |
.gitignore | Thu Nov 05 14:47:19 -0800 2009 | |
| |
MIT-LICENSE | Wed Nov 04 02:35:26 -0800 2009 | |
| |
README.rdoc | Thu Nov 12 00:07:44 -0800 2009 | |
| |
Rakefile | Thu Nov 12 19:31:48 -0800 2009 | |
| |
generators/ | Thu Nov 12 00:07:44 -0800 2009 | |
| |
init.rb | Wed Nov 04 18:26:00 -0800 2009 | |
| |
lib/ | Thu Nov 12 00:12:34 -0800 2009 | |
| |
not_only_but_also.gemspec | Thu Nov 12 19:31:48 -0800 2009 | |
| |
spec/ | Wed Nov 04 18:36:11 -0800 2009 |
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







