Ars*_*Ali 0 ruby oop activerecord ruby-on-rails ruby-on-rails-4
我很难理解我们如何编写以下行:
validates :email, presence: true
Run Code Online (Sandbox Code Playgroud)
我认为这是类方法,因为下面的代码在Rails中完美地执行.
class User < ActiveRecord::Base
self.validates :email, presence: true
end
Run Code Online (Sandbox Code Playgroud)
但是当我转到Rails的源代码时,我才知道这validates是一个实例方法,而不是类方法,而self.validates在类定义中编写给我的印象是它是类方法.
这是它在Rails中的定义:
def validates(*attributes)
defaults = attributes.extract_options!.dup
validations = defaults.slice!(*_validates_default_keys)
raise ArgumentError, "You need to supply at least one attribute" if attributes.empty?
raise ArgumentError, "You need to supply at least one validation" if validations.empty?
defaults[:attributes] = attributes
validations.each do |key, options|
next unless options
key = "#{key.to_s.camelize}Validator"
begin
validator = key.include?('::') ? key.constantize : const_get(key)
rescue NameError
raise ArgumentError, "Unknown validator: '#{key}'"
end
validates_with(validator, defaults.merge(_parse_validates_options(options)))
end
end
Run Code Online (Sandbox Code Playgroud)
实际上是什么?
这是一个类实例方法 :)
正如Sergio在评论中指出的那样,因为Ruby中的每个类都是一个对象(类的实例Class),所以validates是一个Class实例的方法.
你的User类继承了很多东西ActiveRecord::Base.在这个继承的东西中有Validations模块.
旁注: 观看Dave Thomas关于Ruby对象模型的最酷视频 - 事情将变得更加清晰!