Reputation: 807
I switched to Ruby from PHP, and have yet to understand a curious Ruby class behavior where methods are executed outside of the class method definitions (see example below). In PHP, when we wanted to execute anything on class init, we would put it in the constructor method.
Ruby example (Rails):
class Comment < ActiveRecord::Base
belongs_to :post, :counter_cache => true
end
Am I correct in understanding that belongs_to
will be executed on instantiation? And is belongs_to
a class method inherited from ActiveRecord?
Thanks!
Upvotes: 0
Views: 355
Reputation: 369594
In Ruby, everything is executable code. Or, to put it another way: everything is a script. There is no such thing as a "class declaration" or something like that.
Any code that sits in a file, without being inside anything else like a method body, a class body, a module body or a block body, is executed when that file is load
ed (or require
d or require_relative
d). This is called a script body.
Any code that sits inside a class or module body is executed when that class or module is created. (This is the case you are referring to.)
The boring part: any code that sits inside a method body is executed when that method is called, or more precisely, when that method is invoked in response to receiving a message with the same name as the method. (Duh.)
Any code that sits inside a block body is executed when that block is yield
ed to.
Since a class definition is just a script, this means that it can contain any sort of code you want, including method calls:
class Foo
attr_accessor :bar # Yes, attr_accessor is just a method like any other
private # I *bet* you didn't know *that* was a method, too, did you?
end
or conditionals:
class Bar
if blah # e.g. check if the OS is Windows
def foo
# one way
end
else
def foo
# a different way
end
end
end
Upvotes: 3
Reputation: 237110
Yes, it's a class method from ActiveRecord. The method will execute when the class itself is created, not when an instance of it is created.
Upvotes: 1