随着业务逻辑复杂度和team人数的增长,日渐膨胀的Model层代码需要一个统一的代码约定。
以下是我参考了别人的建议后给出的约定:
- require/extend/include (they are dependencies)
- associations, acts_as_*(they are relationships with either other models or other instances of same model)
- constants, scopes, class methods(they are all 'class methods')
- accessors, nested_attributes_for, validates, callbacks, instance methods, delegations(they are all 'instance methods')
- method mark: private, protected
例子:
classArticle<ActiveRecord::Base
require 'json'
include Redis::Search
index :name
has_many :comments
belongs_to :author
acts_as_commentable
acts_as_list
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