2009-04-03
I came up with this:
My personal coding guidelines for where to put stuff in Rails ActiveRecord models
While working with Rails ActiveRecord models recently, I've found that I'm never sure where to put things. Should validations go before relationships? Should class methods come before instance methods? I've started keeping a coding guideline for myself to keep things nice and consistent. It doesn't follow much of a rational order, but it's something, and I've gone with my gut and my gut is happy. Here's what I've come up with:
- includes
- validations
- called class methods
- relationships
- callbacks
- named scopes
- class method definitions
- public method definitions
- private method definitions
- callback method definitions
So, for example, here's how a Post class would look:
class Post < ActiveRecord::Base
# includes
include SpecialPostMethods
# validations
validates_presence_of :title
validates_uniqueness_of :slug
# called class methods
acts_as_textiled :body
# relationships
belongs_to :site
has_many :comments
# callbacks
after_create :save_slug
after_save :ping_technorati
# named scopes
named_scope :most_popular, :order => 'votes DESC'
# class method definitions
def self.post_types
['post', 'page']
end
# public method definitions
def permalink
...
end
private
# private method definitions
def flush_cache_entry
...
end
# callback method definitions
def ping_technorati
...
end
end
Your mileage may vary with this, but I've found that it's really helped me not have to think about where I'm putting stuff. Everything now has a place, so I know I can consistently put things where they should be, or tidy things up when I'm using old code.