Derek J
Derek J

Reputation: 807

Ruby: calling methods on init

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

Answers (3)

J&#246;rg W Mittag
J&#246;rg W Mittag

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 loaded (or required or require_relatived). 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 yielded 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

Chuck
Chuck

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

jtbandes
jtbandes

Reputation: 118761

Yes, that's correct. See also this question.

Upvotes: 0

Related Questions