method invocation in class definition?

前端 未结 1 1593
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-21 01:29
class Person < ActiveRecord::Base
  validates :terms_of_service, :acceptance => true
end

In the above, what is validates from a

相关标签:
1条回答
  • 2020-12-21 01:59

    In Ruby, class declarations are just chunks of code, executed in order.

    It's important to remember that inside a class definition, self points to the class itself. validates is a class method of ActiveRecord. As the class is being defined, code in the definition is executed. The validates method resolves to a class method of ActiveRecord, so is called during class definition.

    In your Person example, it will only print once, because you only define the class once.

    Consider the following:

    class Foo
      def self.validates_nothing(sym)
        (@@syms ||= []) << sym
        puts "!!! Here there be logic"
      end
    
      def validate
        @@syms.each { |s| puts s }
      end
    end
    

    This defines a class with a class method validates_nothing, and an instance method, validate. validates_nothing just gathers whatever arguments are given it, validate just dumps them out.

    class Bar < Foo
      validates_nothing :anything
      validates_nothing :at_all
    end
    

    This defines a subclass. Note that when the class method validates_nothing is called, it prints:

    Here there be logic
    Here there be logic
    

    If we create a new bar and call validate, we get the expected output:

    > Bar.new.validate
    !!!anything
    !!!at_all
    
    0 讨论(0)
提交回复
热议问题