Posted by
guolei
on
May 31, 2011
When the business logic of models becomes complex, it's very helpful to keep a consistent code structure that is agreed by team members.
Following Rails conventions, life is happy. It can be happier if we create conventions for codes in models, especially when there's multiple programmers working on the same model.
One example: (From top to bottom)
- associations
- scopes
- class methods
- validates
- callbacks
- instance methods
Code example:
class Article < ActiveRecord::Base
has_many :comments
belongs_to :author
default_scope order("id desc")
scope :published, where(:published => true)
scope :created_after, lambda{|time| ["created_at >= ?", time]}
class << self
def batch_create(data)
# ...
end
end
validates :title, :presence => true
before_create :init_score
def init_score
self.score = 10
end
def any_instance_method
# ...
end
begin "score related functions" # Group functions by begin .. end
def add_score(score)
# ...
end
end
end

Comments
class << selfnotation just for defining class methods, i prefer to use the more explicitdef self.mymethodbecause then there's no chance to confused a class method with an instance methode...particularly when you have a few class methods and you scroll down below the << definition.