Skinny Controllers and Overweight Models
source link: https://www.devroom.io/2008/08/17/skinny-controllers-and-overweight-models/?utm_campaign=Feed%3A+ariejan+%28ariejan%7Cdevroom.io%29
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Skinny Controllers and Overweight Models
Posted:
2008-08-17
- Last updated:
2019-06-05
Tagged blog ruby rails controllers 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
class User < ActiveRecord::Base
attr_accessor :counter
def up
counter += 1
end
def down
counter -= 1
end
def reset
counter = 0
end
end
You could create a new file lib/counter.rb and include that module in your User model.
class User < ActiveRecord::Base
attr_accessor :counter
include Counter
end
module Counter
def up
counter += 1
end
def down
counter -= 1
end
def reset
counter = 0
end
end
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.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK