Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Method calls declared in class body

I have just started learning ruby on rails and I have encountered code like below:

class Post < ActiveRecord::Base  validates_presence_of   :title  belongs_to :user end 

There are two method calls inside the class body. I have had a hard time finding any ruby documentation that describes how method calls from within a body of a class (but outside of any method) work. All the books I have, only describe how to define class and instance methods and how to call them from within other methods.

The questions I have are: How and when are these methods called? How are they defined? Are they mixins defined in some active record module?

like image 522
Areg Sarkissian Avatar asked Aug 28 '09 02:08

Areg Sarkissian


People also ask

What happens when you call a method in Ruby?

A method in Ruby is a set of expressions that returns a value. With methods, one can organize their code into subroutines that can be easily invoked from other areas of their program. Other languages sometimes refer to this as a function.

What is Ruby class method?

Class Methods are the methods that are defined inside the class, public class methods can be accessed with the help of objects. The method is marked as private by default, when a method is defined outside of the class definition. By default, methods are marked as public which is defined in the class definition.

What is self class in Ruby?

What is self in Ruby. self is a reserved keyword in Ruby that always refers to the current object and classes are also objects, but the object self refers to frequently changes based on the situation or context. So if you're in an instance, self refers to the instance. If you're in a class, self refers to that class.


2 Answers

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.

like image 87
Chuck Avatar answered Oct 05 '22 06:10

Chuck


Yehuda Katz has a nice explanation of this on his blog. See point 4: Class Bodies Aren't Special.

like image 23
John Topley Avatar answered Oct 05 '22 04:10

John Topley