Ruby Method calls declared in class body
The body of a class definition is an execution context for code just like any other. Code there is executed within the context of the class (meaning self
is the class object, which is an instance of Class). You can have locals and instance variables (which will belong to the class object itself rather than instances of the class) and you can call any method that class object responds to. The code is run once the class definition block is finished.
In this case, ActiveRecord::Base defines the class methods validates_presence_of
and belongs_to
.
Yehuda Katz has a nice explanation of this on his blog. See point 4: Class Bodies Aren't Special.
Re: How and when are these methods called?
They're called when the class is loaded. You can put a breakpoint in one of the methods and see that it is called as part of the startup of your rails project.
How are they defined?
They're class methods. Since this is ruby, they could be defined in a number of ways.
Are they mixins defined in some active record module?
In this case, validates_presence_of
is defined in vendor/rails/activerecord/lib/active_record/validations.rb
and belongs_to
is defined in
vendor/rails/activerecord/lib/active_record/associations.rb
. ActiveRecord
is a big system, includes many mixins, modules, etc.
Note, to see where the methods are defined, I use http://www.gotapi.com/rubyrails for each method, see the "Show Source" link at the bottom of the definition.