Skinny Controllers and Overweight Models
All Rails developers know the slogan “Skinny Controllers, Fat Models” and I heartily agree with it. Every conference you go to, you hear it. But there’s a problem! My Fat models got overweight!
What happened? By stuffing all applications logic in the Models, they become fat, very fat. Although this is supposed to be a good thing, I don’t like it. My models get so fat that it takes me forever to scroll through it and find the method I’m working on. There must be a better way!
Well, yes there is: create modules! Normally you’d write a module to reuse your code in different places, but there’s no rule that says you may not use a module only once.
So, I package all related code (e.g. Authentication, state management, managing associated objects, etc) into different modules and place them in the /lib directory. Let’s say you have a a bunch of methods to handle keep a counter on your User model
1class User < ActiveRecord::Base
2 attr_accessor :counter
3
4 def up
5 counter += 1
6 end
7
8 def down
9 counter -= 1
10 end
11
12 def reset
13 counter = 0
14 end
15end
You could create a new file lib/counter.rb and include that module in your User model.
1class User < ActiveRecord::Base
2 attr_accessor :counter
3 include Counter
4end
5
6module Counter
7 def up
8 counter += 1
9 end
10
11 def down
12 counter -= 1
13 end
14
15 def reset
16 counter = 0
17 end
18end
As you can see, this keeps your fat User model clean and makes it easier for you to find code that applies to a certain function.