errors.rb 15.2 KB
Newer Older
1 2
# -*- coding: utf-8 -*-

3
require 'active_support/core_ext/array/conversions'
4 5
require 'active_support/core_ext/string/inflections'

6
module ActiveModel
7
  # == Active \Model \Errors
8
  #
P
prasath 已提交
9
  # Provides a modified +Hash+ that you can include in your object
10
  # for handling error messages and interacting with Action Pack helpers.
11
  #
12
  # A minimal implementation could be:
13
  #
14
  #   class Person
15
  #
16 17
  #     # Required dependency for ActiveModel::Errors
  #     extend ActiveModel::Naming
18
  #
19 20 21
  #     def initialize
  #       @errors = ActiveModel::Errors.new(self)
  #     end
22
  #
23 24
  #     attr_accessor :name
  #     attr_reader   :errors
25
  #
26 27 28
  #     def validate!
  #       errors.add(:name, "can not be nil") if name == nil
  #     end
29
  #
30 31 32 33 34
  #     # The following methods are needed to be minimally implemented
  #
  #     def read_attribute_for_validation(attr)
  #       send(attr)
  #     end
35
  #
N
Neeraj Singh 已提交
36
  #     def Person.human_attribute_name(attr, options = {})
37 38
  #       attr
  #     end
39
  #
N
Neeraj Singh 已提交
40
  #     def Person.lookup_ancestors
41 42
  #       [self]
  #     end
43
  #
44
  #   end
45
  #
46 47
  # The last three methods are required in your object for Errors to be
  # able to generate error messages correctly and also handle multiple
T
Tate Johnson 已提交
48
  # languages. Of course, if you extend your object with ActiveModel::Translation
49
  # you will not need to implement the last two. Likewise, using
50 51
  # ActiveModel::Validations will handle the validation related methods
  # for you.
52
  #
53
  # The above allows you to do:
54
  #
55
  #   p = Person.new
56 57
  #   person.validate!            # => ["can not be nil"]
  #   person.errors.full_messages # => ["name can not be nil"]
58
  #   # etc..
59 60 61
  class Errors
    include Enumerable

62
    CALLBACKS_OPTIONS = [:if, :unless, :on, :allow_nil, :allow_blank, :strict]
63

64 65
    attr_reader :messages

66
    # Pass in the instance of the object that is using the errors object.
67
    #
68 69 70 71 72
    #   class Person
    #     def initialize
    #       @errors = ActiveModel::Errors.new(self)
    #     end
    #   end
73
    def initialize(base)
74
      @base     = base
P
prasath 已提交
75
      @messages = {}
76 77
    end

78
    def initialize_dup(other) # :nodoc:
P
Paweł Kondzior 已提交
79 80 81 82
      @messages = other.messages.dup
      super
    end

83 84
    # Clear the error messages.
    #
85
    #   person.errors.full_messages # => ["name can not be nil"]
86 87
    #   person.errors.clear
    #   person.errors.full_messages # => []
88 89
    def clear
      messages.clear
90
    end
91

92
    # Returns +true+ if the error messages include an error for the given key
93
    # +attribute+, +false+ otherwise.
94
    #
95
    #   person.errors.messages        # => {:name=>["can not be nil"]}
96
    #   person.errors.include?(:name) # => true
97
    #   person.errors.include?(:age)  # => false
98 99
    def include?(attribute)
      (v = messages[attribute]) && v.any?
100
    end
101
    # aliases include?
102
    alias :has_key? :include?
103

104 105
    # Get messages for +key+.
    #
106
    #   person.errors.messages   # => {:name=>["can not be nil"]}
107 108
    #   person.errors.get(:name) # => ["can not be nil"]
    #   person.errors.get(:age)  # => nil
109 110 111 112
    def get(key)
      messages[key]
    end

113 114 115 116 117
    # Set messages for +key+ to +value+.
    #
    #   person.errors.get(:name) # => ["can not be nil"]
    #   person.errors.set(:name, ["can't be nil"])
    #   person.errors.get(:name) # => ["can't be nil"]
118 119 120
    def set(key, value)
      messages[key] = value
    end
121

122 123 124 125 126
    # Delete messages for +key+. Returns the deleted messages.
    #
    #   person.errors.get(:name)    # => ["can not be nil"]
    #   person.errors.delete(:name) # => ["can not be nil"]
    #   person.errors.get(:name)    # => nil
127 128 129 130
    def delete(key)
      messages.delete(key)
    end

131
    # When passed a symbol or a name of a method, returns an array of errors
132
    # for the method.
133
    #
134 135
    #   person.errors[:name]  # => ["can not be nil"]
    #   person.errors['name'] # => ["can not be nil"]
136
    def [](attribute)
S
Subba Rao Pasupuleti 已提交
137
      get(attribute.to_sym) || set(attribute.to_sym, [])
138 139
    end

140
    # Adds to the supplied attribute the supplied error message.
141
    #
142 143
    #   person.errors[:name] = "must be set"
    #   person.errors[:name] # => ['must be set']
144
    def []=(attribute, error)
P
Paweł Kondzior 已提交
145
      self[attribute] << error
146 147
    end

148
    # Iterates through each error key, value pair in the error messages hash.
149
    # Yields the attribute and the error for that attribute. If the attribute
150
    # has more than one error message, yields once for each error message.
151
    #
152 153
    #   person.errors.add(:name, "can't be blank")
    #   person.errors.each do |attribute, error|
154 155
    #     # Will yield :name and "can't be blank"
    #   end
156
    #
157 158
    #   person.errors.add(:name, "must be specified")
    #   person.errors.each do |attribute, error|
159 160 161
    #     # Will yield :name and "can't be blank"
    #     # then yield :name and "must be specified"
    #   end
162
    def each
163
      messages.each_key do |attribute|
164 165 166 167
        self[attribute].each { |error| yield attribute, error }
      end
    end

168
    # Returns the number of error messages.
169
    #
170 171 172 173
    #   person.errors.add(:name, "can't be blank")
    #   person.errors.size # => 1
    #   person.errors.add(:name, "must be specified")
    #   person.errors.size # => 2
174 175 176 177
    def size
      values.flatten.size
    end

178 179
    # Returns all message values.
    #
180
    #   person.errors.messages # => {:name=>["can not be nil", "must be specified"]}
181
    #   person.errors.values   # => [["can not be nil", "must be specified"]]
182 183 184 185
    def values
      messages.values
    end

186 187
    # Returns all message keys.
    #
188
    #   person.errors.messages # => {:name=>["can not be nil", "must be specified"]}
189
    #   person.errors.keys     # => [:name]
190 191 192 193
    def keys
      messages.keys
    end

194
    # Returns an array of error messages, with the attribute name included.
195
    #
196 197 198
    #   person.errors.add(:name, "can't be blank")
    #   person.errors.add(:name, "must be specified")
    #   person.errors.to_a # => ["name can't be blank", "name must be specified"]
199
    def to_a
200 201 202
      full_messages
    end

203
    # Returns the number of error messages.
204 205 206 207 208
    #
    #   person.errors.add(:name, "can't be blank")
    #   person.errors.count # => 1
    #   person.errors.add(:name, "must be specified")
    #   person.errors.count # => 2
209 210
    def count
      to_a.size
211 212
    end

213
    # Returns +true+ if no errors are found, +false+ otherwise.
214
    # If the error message is a string it can be empty.
215 216 217
    #
    #   person.errors.full_messages # => ["name can not be nil"]
    #   person.errors.empty?        # => false
218
    def empty?
219
      all? { |k, v| v && v.empty? && !v.is_a?(String) }
220
    end
221
    # aliases empty?
222
    alias_method :blank?, :empty?
223

224
    # Returns an xml formatted representation of the Errors hash.
225
    #
226 227 228
    #   person.errors.add(:name, "can't be blank")
    #   person.errors.add(:name, "must be specified")
    #   person.errors.to_xml
229
    #   # =>
230 231 232 233 234
    #   #  <?xml version=\"1.0\" encoding=\"UTF-8\"?>
    #   #  <errors>
    #   #    <error>name can't be blank</error>
    #   #    <error>name must be specified</error>
    #   #  </errors>
235
    def to_xml(options={})
C
Carlos Antonio da Silva 已提交
236
      to_a.to_xml({ :root => "errors", :skip_types => true }.merge!(options))
237
    end
238

239 240 241
    # Returns a Hash that can be used as the JSON representation for this
    # object. You can pass the <tt>:full_messages</tt> option. This determines
    # if the json object should contain full messages or not (false by default).
242
    #
243 244
    #   person.as_json                      # => {:name=>["can not be nil"]}
    #   person.as_json(full_messages: true) # => {:name=>["name can not be nil"]}
245
    def as_json(options=nil)
246 247 248
      to_hash(options && options[:full_messages])
    end

249 250 251
    # Returns a Hash of attributes with their error messages. If +full_messages+
    # is +true+, it will contain full messages (see +full_message+).
    #
252 253
    #   person.to_hash       # => {:name=>["can not be nil"]}
    #   person.to_hash(true) # => {:name=>["name can not be nil"]}
254 255 256 257
    def to_hash(full_messages = false)
      if full_messages
        messages = {}
        self.messages.each do |attribute, array|
C
Carlos Antonio da Silva 已提交
258
          messages[attribute] = array.map { |message| full_message(attribute, message) }
259 260 261 262 263
        end
        messages
      else
        self.messages.dup
      end
264
    end
265

266 267 268
    # Adds +message+ to the error messages on +attribute+. More than one error
    # can be added to the same +attribute+. If no +message+ is supplied,
    # <tt>:invalid</tt> is assumed.
269
    #
270 271 272 273 274 275
    #   person.errors.add(:name)
    #   # => ["is invalid"]
    #   person.errors.add(:name, 'must be implemented')
    #   # => ["is invalid", "must be implemented"]
    #
    #   person.errors.messages
276
    #   # => {:name=>["must be implemented", "is invalid"]}
277
    #
278 279
    # If +message+ is a symbol, it will be translated using the appropriate
    # scope (see +generate_message+).
280
    #
281 282
    # If +message+ is a proc, it will be called, allowing for things like
    # <tt>Time.now</tt> to be used within an error.
283 284 285
    #
    # If the <tt>:strict</tt> option is set to true will raise
    # ActiveModel::StrictValidationFailed instead of adding the error.
286
    # <tt>:strict</tt> option can also be set to any other exception.
287 288
    #
    #   person.errors.add(:name, nil, strict: true)
289
    #   # => ActiveModel::StrictValidationFailed: name is invalid
290
    #   person.errors.add(:name, nil, strict: NameIsInvalid)
291
    #   # => NameIsInvalid: name is invalid
292 293
    #
    #   person.errors.messages # => {}
294
    def add(attribute, message = nil, options = {})
295
      message = normalize_message(attribute, message, options)
296 297 298
      if exception = options[:strict]
        exception = ActiveModel::StrictValidationFailed if exception == true
        raise exception, full_message(attribute, message)
299
      end
300

301 302 303
      self[attribute] << message
    end

304 305
    # Will add an error message to each of the attributes in +attributes+
    # that is empty.
306 307 308
    #
    #   person.errors.add_on_empty(:name)
    #   person.errors.messages
309
    #   # => {:name=>["can't be empty"]}
310
    def add_on_empty(attributes, options = {})
311
      [attributes].flatten.each do |attribute|
P
Pratik Naik 已提交
312
        value = @base.send(:read_attribute_for_validation, attribute)
313
        is_empty = value.respond_to?(:empty?) ? value.empty? : false
314
        add(attribute, :empty, options) if value.nil? || is_empty
315 316 317
      end
    end

318 319
    # Will add an error message to each of the attributes in +attributes+ that
    # is blank (using Object#blank?).
320 321 322
    #
    #   person.errors.add_on_blank(:name)
    #   person.errors.messages
323
    #   # => {:name=>["can't be blank"]}
324
    def add_on_blank(attributes, options = {})
325
      [attributes].flatten.each do |attribute|
P
Pratik Naik 已提交
326
        value = @base.send(:read_attribute_for_validation, attribute)
327
        add(attribute, :blank, options) if value.blank?
328 329 330
      end
    end

331 332 333 334 335
    # Returns +true+ if an error on the attribute with the given message is
    # present, +false+ otherwise. +message+ is treated the same as for +add+.
    #
    #   person.errors.add :name, :blank
    #   person.errors.added? :name, :blank # => true
336 337 338 339 340
    def added?(attribute, message = nil, options = {})
      message = normalize_message(attribute, message, options)
      self[attribute].include? message
    end

341 342
    # Returns all the full error messages in an array.
    #
343
    #   class Person
344
    #     validates_presence_of :name, :address, :email
345
    #     validates_length_of :name, in: 5..30
346 347
    #   end
    #
348 349 350
    #   person = Person.create(address: '123 First St.')
    #   person.errors.full_messages
    #   # => ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Email can't be blank"]
351
    def full_messages
352 353
      map { |attribute, message| full_message(attribute, message) }
    end
354

355 356
    # Returns a full message for a given attribute.
    #
357
    #   person.errors.full_message(:name, 'is invalid') # => "Name is invalid"
358 359
    def full_message(attribute, message)
      return message if attribute == :base
360
      attr_name = attribute.to_s.tr('.', '_').humanize
361 362 363 364 365 366
      attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
      I18n.t(:"errors.format", {
        :default   => "%{attribute} %{message}",
        :attribute => attr_name,
        :message   => message
      })
367 368
    end

369
    # Translates an error message in its default scope
370 371
    # (<tt>activemodel.errors.messages</tt>).
    #
372
    # Error messages are first looked up in <tt>models.MODEL.attributes.ATTRIBUTE.MESSAGE</tt>,
373 374 375 376 377
    # if it's not there, it's looked up in <tt>models.MODEL.MESSAGE</tt> and if
    # that is not there also, it returns the translation of the default message
    # (e.g. <tt>activemodel.errors.messages.MESSAGE</tt>). The translated model
    # name, translated attribute name and the value are available for
    # interpolation.
378
    #
379
    # When using inheritance in your models, it will check all the inherited
380
    # models too, but only if the model itself hasn't been found. Say you have
381
    # <tt>class Admin < User; end</tt> and you wanted the translation for
382
    # the <tt>:blank</tt> error message for the <tt>title</tt> attribute,
383
    # it looks for these translations:
384
    #
385 386 387 388 389 390 391 392
    # * <tt>activemodel.errors.models.admin.attributes.title.blank</tt>
    # * <tt>activemodel.errors.models.admin.blank</tt>
    # * <tt>activemodel.errors.models.user.attributes.title.blank</tt>
    # * <tt>activemodel.errors.models.user.blank</tt>
    # * any default you provided through the +options+ hash (in the <tt>activemodel.errors</tt> scope)
    # * <tt>activemodel.errors.messages.blank</tt>
    # * <tt>errors.attributes.title.blank</tt>
    # * <tt>errors.messages.blank</tt>
393 394 395
    def generate_message(attribute, type = :invalid, options = {})
      type = options.delete(:message) if options[:message].is_a?(Symbol)

396 397 398 399 400 401 402
      if @base.class.respond_to?(:i18n_scope)
        defaults = @base.class.lookup_ancestors.map do |klass|
          [ :"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.i18n_key}.attributes.#{attribute}.#{type}",
            :"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.i18n_key}.#{type}" ]
        end
      else
        defaults = []
403
      end
404

405
      defaults << options.delete(:message)
406
      defaults << :"#{@base.class.i18n_scope}.errors.messages.#{type}" if @base.class.respond_to?(:i18n_scope)
407 408
      defaults << :"errors.attributes.#{attribute}.#{type}"
      defaults << :"errors.messages.#{type}"
409 410 411

      defaults.compact!
      defaults.flatten!
412 413

      key = defaults.shift
414
      value = (attribute != :base ? @base.send(:read_attribute_for_validation, attribute) : nil)
415

416 417
      options = {
        :default => defaults,
418 419
        :model => @base.class.model_name.human,
        :attribute => @base.class.human_attribute_name(attribute),
420
        :value => value
C
Carlos Antonio da Silva 已提交
421
      }.merge!(options)
422 423 424

      I18n.translate(key, options)
    end
425 426 427 428 429

  private
    def normalize_message(attribute, message, options)
      message ||= :invalid

C
Carlos Antonio da Silva 已提交
430 431
      case message
      when Symbol
432
        generate_message(attribute, message, options.except(*CALLBACKS_OPTIONS))
C
Carlos Antonio da Silva 已提交
433
      when Proc
434 435 436 437 438
        message.call
      else
        message
      end
    end
439
  end
440

441
  # Raised when a validation cannot be corrected by end users and are considered
442
  # exceptional.
443 444 445 446 447 448 449 450 451 452 453 454 455
  #
  #   class Person
  #     include ActiveModel::Validations
  #
  #     attr_accessor :name
  #
  #     validates_presence_of :name, strict: true
  #   end
  #
  #   person = Person.new
  #   person.name = nil
  #   person.valid?
  #   # => ActiveModel::StrictValidationFailed: Name can't be blank
456 457
  class StrictValidationFailed < StandardError
  end
458
end