Skip to content

Instantly share code, notes, and snippets.

@ltw
Created February 21, 2011 01:29
Show Gist options
  • Save ltw/836525 to your computer and use it in GitHub Desktop.
Save ltw/836525 to your computer and use it in GitHub Desktop.
Order of a standard Model
class Model < ParentModel
include Foo::Bar
extend Bar::Baz
acts_as_authentic
dsl_specific_flags
module InternalModule
...
end
default_scope :order => 'id ASC'
belongs_to :foo
has_one :baz
has_many :bars
has_many :maz, :through => :daz
has_and_belongs_to_many :jaz
serialize :bars, Hash
...
before_validation :foo
after_validation :bar
before_save :baz
before_create :taz
after_create :daz
after_save :maz
after_commit :laz
...
validates_presence_of :id
validates_uniqueness_of :id
validates_inclusion_of :rating, :in => [1..10]
validates_numericality_of :taz
...
accepts_nested_attributes_for :foobar
scope :by_name, :order => 'name ASC'
scope :lambda_scope, :lambda => { |lambda| { ... } }
...
attr_reader :foobaz
attr_accessor :foobar
delegate :barbaz, :to => :foo
...
def self.class_method
end
def instance_method
end
protected
def self.class_method
end
def instance_method
end
private
def self.class_method
end
def instance_method
end
end
@timriley
Copy link

Don't forget callbacks. I tend to put them fairly high in the class definition. If I recall correctly, in the past I've experienced some problems because they were declared below some other things.

@ltw
Copy link
Author

ltw commented Feb 21, 2011

Good point. I added them. :)

@timriley
Copy link

Now how about "virtual" attributes created via attr_accessor? Where do you put them?

@timriley
Copy link

And what about other common class-scope DSLs? One that comes to mind is the Thinking Sphinx define_index block.

@timriley
Copy link

Other examples of the above are CarrierWave's mount_uploader and AuthLogics acts_as_authentic.

@timriley
Copy link

Oh, what about accepts_nested_attributes_for?

@lenary
Copy link

lenary commented Apr 27, 2011

wouldn't you put accepts... beside the association it applied to? i'd say that made more sense

and put all the scopes (default and normal ones) together

@radar
Copy link

radar commented May 8, 2011

+1 @lenary, I want to know if a model accepts nested attributes for one of its associations so I tend to put this on its own lines:

 belongs_to :foo

 has_many :bars
 accepts_nested_attributes_for :bars

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment