简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM