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

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

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

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

65 66
    attr_reader :messages

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

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

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

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

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

114 115 116 117 118
    # 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"]
119 120 121
    def set(key, value)
      messages[key] = value
    end
122

123 124 125 126 127
    # 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
128 129 130 131
    def delete(key)
      messages.delete(key)
    end

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

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

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

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

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

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

195
    # Returns an array of error messages, with the attribute name included.
196
    #
197 198 199
    #   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"]
200
    def to_a
201 202 203
      full_messages
    end

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

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

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

240 241 242
    # 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).
243 244 245
    #
    #   person.as_json                      # => { :name => ["can not be nil"] }
    #   person.as_json(full_messages: true) # => { :name => ["name can not be nil"] }
246
    def as_json(options=nil)
247 248 249
      to_hash(options && options[:full_messages])
    end

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

267 268 269 270
    # 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.
    #
271 272 273 274 275 276 277 278
    #   person.errors.add(:name)
    #   # => ["is invalid"]
    #   person.errors.add(:name, 'must be implemented')
    #   # => ["is invalid", "must be implemented"]
    #
    #   person.errors.messages
    #   # => { :name => ["must be implemented", "is invalid"] }
    #
279 280
    # If +message+ is a symbol, it will be translated using the appropriate
    # scope (see +generate_message+).
281
    #
282 283
    # If +message+ is a proc, it will be called, allowing for things like
    # <tt>Time.now</tt> to be used within an error.
284
    def add(attribute, message = nil, options = {})
285
      message = normalize_message(attribute, message, options)
286
      if options[:strict]
287
        raise ActiveModel::StrictValidationFailed, full_message(attribute, message)
288
      end
289

290 291 292
      self[attribute] << message
    end

293 294
    # Will add an error message to each of the attributes in +attributes+
    # that is empty.
295 296 297 298
    #
    #   person.errors.add_on_empty(:name)
    #   person.errors.messages
    #   # => { :name => ["can't be empty"] }
299
    def add_on_empty(attributes, options = {})
300
      [attributes].flatten.each do |attribute|
P
Pratik Naik 已提交
301
        value = @base.send(:read_attribute_for_validation, attribute)
302
        is_empty = value.respond_to?(:empty?) ? value.empty? : false
303
        add(attribute, :empty, options) if value.nil? || is_empty
304 305 306
      end
    end

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

320 321 322 323 324
    # 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
325 326 327 328 329
    def added?(attribute, message = nil, options = {})
      message = normalize_message(attribute, message, options)
      self[attribute].include? message
    end

330 331
    # Returns all the full error messages in an array.
    #
332
    #   class Person
333
    #     validates_presence_of :name, :address, :email
334
    #     validates_length_of :name, in: 5..30
335 336
    #   end
    #
337 338 339
    #   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"]
340
    def full_messages
341 342
      map { |attribute, message| full_message(attribute, message) }
    end
343

344 345
    # Returns a full message for a given attribute.
    #
346
    #   person.errors.full_message(:name, 'is invalid') # => "Name is invalid"
347 348
    def full_message(attribute, message)
      return message if attribute == :base
349
      attr_name = attribute.to_s.tr('.', '_').humanize
350 351 352 353 354 355
      attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
      I18n.t(:"errors.format", {
        :default   => "%{attribute} %{message}",
        :attribute => attr_name,
        :message   => message
      })
356 357
    end

358
    # Translates an error message in its default scope
359 360
    # (<tt>activemodel.errors.messages</tt>).
    #
361
    # Error messages are first looked up in <tt>models.MODEL.attributes.ATTRIBUTE.MESSAGE</tt>,
362 363 364 365 366
    # 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.
367
    #
368
    # When using inheritance in your models, it will check all the inherited
369
    # models too, but only if the model itself hasn't been found. Say you have
370
    # <tt>class Admin < User; end</tt> and you wanted the translation for
371
    # the <tt>:blank</tt> error message for the <tt>title</tt> attribute,
372
    # it looks for these translations:
373
    #
374 375 376 377 378 379 380 381
    # * <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>
382 383 384
    def generate_message(attribute, type = :invalid, options = {})
      type = options.delete(:message) if options[:message].is_a?(Symbol)

385 386 387 388 389 390 391
      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 = []
392
      end
393

394
      defaults << options.delete(:message)
395
      defaults << :"#{@base.class.i18n_scope}.errors.messages.#{type}" if @base.class.respond_to?(:i18n_scope)
396 397
      defaults << :"errors.attributes.#{attribute}.#{type}"
      defaults << :"errors.messages.#{type}"
398 399 400

      defaults.compact!
      defaults.flatten!
401 402

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

405 406
      options = {
        :default => defaults,
407 408
        :model => @base.class.model_name.human,
        :attribute => @base.class.human_attribute_name(attribute),
409
        :value => value
C
Carlos Antonio da Silva 已提交
410
      }.merge!(options)
411 412 413

      I18n.translate(key, options)
    end
414 415 416 417 418

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

C
Carlos Antonio da Silva 已提交
419 420
      case message
      when Symbol
421
        generate_message(attribute, message, options.except(*CALLBACKS_OPTIONS))
C
Carlos Antonio da Silva 已提交
422
      when Proc
423 424 425 426 427
        message.call
      else
        message
      end
    end
428
  end
429 430 431

  class StrictValidationFailed < StandardError
  end
432
end