This ... is a bit complicated, but the short answer is that validates
is a method of the Person
class inherited from ActiveRecord::Base
. This line would also be written validates(:terms_of_service, :acceptance => true)
.
Ruby, like many interpreted languages, effectively “executes” class definitions, so when it encounters a validates
string, it sees it as a method call, where the current self
object is an instance of the Class
class, which represents the Person
class that inherits from ActiveRecord::Base
. It calls a method that connects the validator to the Person
class.
You can read about the method here - but note that this adds more confusion, since it lists the method as an instance method of ActiveModel::Validations::ClassMethods
. A? Well, Ruby has two ways to use the functionality from another Module
and put it in its own class - you can either include
module (in this case, its instance methods become instance methods of your class) or extend
module (in this case its instance methods become class methods your class).
So to summarize: validates
declared as an instance method of ActiveModel::Validations::ClassMethods
, which extend
ed in ActiveRecord::Base
. Therefore, validates
is a method of the ActiveRecord::Base
class and, by inheritance, Person
. A line in a code snippet is just a method call.
However, having said all this, most rubists and Railsists will largely ignore these facts; validates
is what is called a “decorator,” and most people will simply read it as a statement about Person
.
source share