Validation Reflection

本插件提供两个 ‘类’ 方法

  • ModelClass.reflect_on_all_validations
  • ModelClass.reflect_on_validations_for(:property)

返回的是其所校验的对象 id (以数组的形式)和该所对就的 属性
例如:

 class Person < ActiveRecord::Base
    validates_presence_of :name
    validates_numericality_of :size, :only_integer => true
  end

  refl = Person.reflect_on_validations_for(:name)
  refl[0].macro
  # => :validates_presence_of

  refl = Person.reflect_on_validations_for(:size)
  refl[0].macro
  # => :validates_numericality_of
  refl[0].options
  # => { :only_integer => true }

这是源代码里对这两个方法的定义

module ClassMethods

    include ::ValidationReflection

    # Returns an array of MacroReflection objects for all validations in the class
    def reflect_on_all_validations
      self.read_inheritable_attribute(:reflected_validations) || []
    end

    # Returns an array of MacroReflection objects for all validations defined for the field +attr_name+.
    def reflect_on_validations_for(attr_name)
      self.reflect_on_all_validations.select do |reflection|
        reflection.name == attr_name.to_sym
      end
    end

你可能感兴趣的:(Validation Reflection)