validations.rb 7.0 KB
Newer Older
1
require 'active_support/core_ext/array/extract_options'
J
Jeremy Kemper 已提交
2
require 'active_support/core_ext/array/wrap'
3
require 'active_support/core_ext/class/attribute'
4
require 'active_support/core_ext/hash/keys'
5
require 'active_support/core_ext/hash/except'
J
Joshua Peek 已提交
6
require 'active_model/errors'
7
require 'active_model/validations/callbacks'
8

9
module ActiveModel
10 11

  # == Active Model Validations
12
  #
13
  # Provides a full validation framework to your objects.
14
  #
15
  # A minimal implementation could be:
16
  #
17 18
  #   class Person
  #     include ActiveModel::Validations
19
  #
20 21 22 23 24 25
  #     attr_accessor :first_name, :last_name
  #
  #     validates_each :first_name, :last_name do |record, attr, value|
  #       record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
  #     end
  #   end
26
  #
27
  # Which provides you with the full standard validation stack that you
28
  # know from Active Record:
29
  #
30
  #   person = Person.new
31 32 33
  #   person.valid?                   # => true
  #   person.invalid?                 # => false
  #
34
  #   person.first_name = 'zoolander'
35 36 37
  #   person.valid?                   # => false
  #   person.invalid?                 # => true
  #   person.errors                   # => #<OrderedHash {:first_name=>["starts with z."]}>
38
  #
39 40
  # Note that ActiveModel::Validations automatically adds an +errors+ method
  # to your instances initialized with a new ActiveModel::Errors object, so
41
  # there is no need for you to do this manually.
42
  #
43
  module Validations
J
Joshua Peek 已提交
44
    extend ActiveSupport::Concern
45
    include ActiveSupport::Callbacks
J
Joshua Peek 已提交
46 47

    included do
48
      extend ActiveModel::Translation
49

50 51
      extend  HelperMethods
      include HelperMethods
52

53
      attr_accessor :validation_context
54
      define_callbacks :validate, :scope => :name
55

56
      class_attribute :_validators
57
      self._validators = Hash.new { |h,k| h[k] = [] }
58 59 60
    end

    module ClassMethods
61 62
      # Validates each attribute against a block.
      #
63 64
      #   class Person
      #     include ActiveModel::Validations
65
      #
66 67
      #     attr_accessor :first_name, :last_name
      #
68
      #     validates_each :first_name, :last_name do |record, attr, value|
69
      #       record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
70 71 72 73
      #     end
      #   end
      #
      # Options:
74
      # * <tt>:on</tt> - Specifies when this validation is active (default is
75
      #   <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
76 77
      # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
      # * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
78 79 80 81
      # * <tt>:if</tt> - Specifies a method, proc or string to call to determine
      #   if the validation should occur (e.g. <tt>:if => :allow_validation</tt>,
      #   or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The method,
      #   proc or string should return or evaluate to a true or false value.
82
      # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
83 84
      #   not occur (e.g. <tt>:unless => :skip_validation</tt>, or
      #   <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).  The
85 86 87 88 89 90
      #   method, proc or string should return or evaluate to a true or false value.
      def validates_each(*attr_names, &block)
        options = attr_names.extract_options!.symbolize_keys
        validates_with BlockValidator, options.merge(:attributes => attr_names.flatten), &block
      end

D
David Heinemeier Hansson 已提交
91
      # Adds a validation method or block to the class. This is useful when
92
      # overriding the +validate+ instance method becomes too unwieldy and
D
David Heinemeier Hansson 已提交
93 94 95 96
      # you're looking for more descriptive declaration of your validations.
      #
      # This can be done with a symbol pointing to a method:
      #
97 98
      #   class Comment
      #     include ActiveModel::Validations
99
      #
D
David Heinemeier Hansson 已提交
100 101 102
      #     validate :must_be_friends
      #
      #     def must_be_friends
103
      #       errors.add(:base, "Must be friends to leave a comment") unless commenter.friend_of?(commentee)
D
David Heinemeier Hansson 已提交
104 105 106
      #     end
      #   end
      #
107
      # Or with a block which is passed with the current record to be validated:
D
David Heinemeier Hansson 已提交
108
      #
109 110 111
      #   class Comment
      #     include ActiveModel::Validations
      #
D
David Heinemeier Hansson 已提交
112 113 114 115 116
      #     validate do |comment|
      #       comment.must_be_friends
      #     end
      #
      #     def must_be_friends
117
      #       errors.add(:base, ("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
D
David Heinemeier Hansson 已提交
118 119 120
      #     end
      #   end
      #
121
      def validate(*args, &block)
122 123 124
        options = args.extract_options!
        if options.key?(:on)
          options = options.dup
J
Jeremy Kemper 已提交
125
          options[:if] = Array.wrap(options[:if])
126
          options[:if] << "validation_context == :#{options[:on]}"
127
        end
128
        args << options
129
        set_callback(:validate, *args, &block)
130
      end
131

132
      # List all validators that are being used to validate the model using
133
      # +validates_with+ method.
134 135 136 137 138 139 140 141 142
      def validators
        _validators.values.flatten.uniq
      end

      # List all validators that being used to validate a specific attribute.
      def validators_on(attribute)
        _validators[attribute.to_sym]
      end

143
      # Check if method is an attribute method or not.
144 145 146
      def attribute_method?(attribute)
        method_defined?(attribute)
      end
147 148 149 150 151 152 153

      # Copy validators on inheritance.
      def inherited(base)
        dup = _validators.dup
        base._validators = dup.each { |k, v| dup[k] = v.dup }
        super
      end
154 155
    end

156 157
    # Returns the Errors object that holds all information about attribute error messages.
    def errors
158
      @errors ||= Errors.new(self)
159
    end
160

161 162 163
    # Runs all the specified validations and returns true if no errors were added
    # otherwise false. Context can optionally be supplied to define which callbacks
    # to test against (the context is defined on the validations using :on).
164 165
    def valid?(context = nil)
      current_context, self.validation_context = validation_context, context
166
      errors.clear
167
      run_validations!
168 169
    ensure
      self.validation_context = current_context
170
    end
171

172
    # Performs the opposite of <tt>valid?</tt>. Returns true if errors were added,
173
    # false otherwise.
174 175
    def invalid?(context = nil)
      !valid?(context)
176
    end
177

178 179
    # Hook method defining how an attribute value should be retrieved. By default
    # this is assumed to be an instance named after the attribute. Override this
180 181 182
    # method in subclasses should you need to retrieve the value for a given
    # attribute differently:
    #
183 184 185 186 187 188 189 190 191 192 193 194
    #   class MyClass
    #     include ActiveModel::Validations
    #
    #     def initialize(data = {})
    #       @data = data
    #     end
    #
    #     def read_attribute_for_validation(key)
    #       @data[key]
    #     end
    #   end
    #
195
    alias :read_attribute_for_validation :send
196 197

  protected
198

199 200 201 202
    def run_validations!
      _run_validate_callbacks
      errors.empty?
    end
203
  end
204 205 206 207 208
end

Dir[File.dirname(__FILE__) + "/validations/*.rb"].sort.each do |path|
  filename = File.basename(path)
  require "active_model/validations/#{filename}"
209
end