malcoauri
malcoauri

Reputation: 12189

Executing method in Ruby class

There is the following code in RoR:

class Product < ActiveRecord::Base
  validates :title, :description, :image_url, presence: true
end

I've read some Ruby books, but I didn't see in OOP paragraph any information about executing methods of class in class (not other method) body! What is it? How does it work? When is this method executed? Please, make me clear in this question. Thanks.

Upvotes: 0

Views: 95

Answers (1)

sawa
sawa

Reputation: 168101

A method is executed when it is called. In the context of a class body, self becomes that class. self as a receiver can be omitted, so validates here is the same as Product.validates ... or self.validates .... validates is a class method on Active::Base, and is called during the class definition.


In my understanding, self and an implicit receiver mean different things depending on where it is located.

module Foo
  # module body
  def # method name
    # method body
  end
end
  1. In a module body
    • self: the module
    • implicit receiver: the module
  2. In a method name
    • self: the module
    • implicit receiver: an instance of the class
  3. In a method body
    • self: the receiver in the method name
    • implicit receiver: the receiver in the method name

Upvotes: 2

Related Questions