~michaelforrest/use-case-mapper/trunk

« back to all changes in this revision

Viewing changes to vendor/rails/activerecord/lib/active_record/validations.rb

  • Committer: Michael Forrest
  • Date: 2010-10-15 16:28:50 UTC
  • Revision ID: michael.forrest@canonical.com-20101015162850-tj2vchanv0kr0dun
refrozeĀ gems

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
module ActiveRecord
 
2
  # Raised by <tt>save!</tt> and <tt>create!</tt> when the record is invalid.  Use the
 
3
  # +record+ method to retrieve the record which did not validate.
 
4
  #   begin
 
5
  #     complex_operation_that_calls_save!_internally
 
6
  #   rescue ActiveRecord::RecordInvalid => invalid
 
7
  #     puts invalid.record.errors
 
8
  #   end
 
9
  class RecordInvalid < ActiveRecordError
 
10
    attr_reader :record
 
11
    def initialize(record)
 
12
      @record = record
 
13
      errors = @record.errors.full_messages.join(I18n.t('support.array.words_connector', :default => ', '))
 
14
      super(I18n.t('activerecord.errors.messages.record_invalid', :errors => errors))
 
15
    end
 
16
  end
 
17
 
 
18
  class Error
 
19
    attr_accessor :base, :attribute, :type, :message, :options
 
20
 
 
21
    def initialize(base, attribute, type = nil, options = {})
 
22
      self.base      = base
 
23
      self.attribute = attribute
 
24
      self.type      = type || :invalid
 
25
      self.options   = options
 
26
      self.message   = options.delete(:message) || self.type
 
27
    end
 
28
 
 
29
    def message
 
30
      # When type is a string, it means that we do not have to do a lookup, because
 
31
      # the user already sent the "final" message.
 
32
      type.is_a?(String) ? type : generate_message(default_options)
 
33
    end
 
34
 
 
35
    def full_message
 
36
      attribute.to_s == 'base' ? message : generate_full_message(default_options)
 
37
    end
 
38
 
 
39
    alias :to_s :message
 
40
 
 
41
    def value
 
42
      @base.respond_to?(attribute) ? @base.send(attribute) : nil
 
43
    end
 
44
 
 
45
    protected
 
46
 
 
47
      # Translates an error message in it's default scope (<tt>activerecord.errrors.messages</tt>).
 
48
      # Error messages are first looked up in <tt>models.MODEL.attributes.ATTRIBUTE.MESSAGE</tt>, if it's not there,
 
49
      # it's looked up in <tt>models.MODEL.MESSAGE</tt> and if that is not there it returns the translation of the
 
50
      # default message (e.g. <tt>activerecord.errors.messages.MESSAGE</tt>). The translated model name,
 
51
      # translated attribute name and the value are available for interpolation.
 
52
      #
 
53
      # When using inheritence in your models, it will check all the inherited models too, but only if the model itself
 
54
      # hasn't been found. Say you have <tt>class Admin < User; end</tt> and you wanted the translation for the <tt>:blank</tt>
 
55
      # error +message+ for the <tt>title</tt> +attribute+, it looks for these translations:
 
56
      #
 
57
      # <ol>
 
58
      # <li><tt>activerecord.errors.models.admin.attributes.title.blank</tt></li>
 
59
      # <li><tt>activerecord.errors.models.admin.blank</tt></li>
 
60
      # <li><tt>activerecord.errors.models.user.attributes.title.blank</tt></li>
 
61
      # <li><tt>activerecord.errors.models.user.blank</tt></li>
 
62
      # <li><tt>activerecord.errors.messages.blank</tt></li>
 
63
      # <li>any default you provided through the +options+ hash (in the activerecord.errors scope)</li>
 
64
      # </ol>
 
65
      def generate_message(options = {})
 
66
        keys = @base.class.self_and_descendants_from_active_record.map do |klass|
 
67
          [ :"models.#{klass.name.underscore}.attributes.#{attribute}.#{@message}",
 
68
            :"models.#{klass.name.underscore}.#{@message}" ]
 
69
        end.flatten
 
70
 
 
71
        keys << options.delete(:default)
 
72
        keys << :"messages.#{@message}"
 
73
        keys << @message if @message.is_a?(String)
 
74
        keys << @type unless @type == @message
 
75
        keys.compact!
 
76
 
 
77
        options.merge!(:default => keys)
 
78
        I18n.translate(keys.shift, options)
 
79
      end
 
80
 
 
81
      # Wraps an error message into a full_message format.
 
82
      #
 
83
      # The default full_message format for any locale is <tt>"{{attribute}} {{message}}"</tt>.
 
84
      # One can specify locale specific default full_message format by storing it as a
 
85
      # translation for the key <tt>:"activerecord.errors.full_messages.format"</tt>.
 
86
      #
 
87
      # Additionally one can specify a validation specific error message format by
 
88
      # storing a translation for <tt>:"activerecord.errors.full_messages.[message_key]"</tt>.
 
89
      # E.g. the full_message format for any validation that uses :blank as a message
 
90
      # key (such as validates_presence_of) can be stored to <tt>:"activerecord.errors.full_messages.blank".</tt>
 
91
      #
 
92
      # Because the message key used by a validation can be overwritten on the
 
93
      # <tt>validates_*</tt> class macro level one can customize the full_message format for
 
94
      # any particular validation:
 
95
      #
 
96
      #   # app/models/article.rb
 
97
      #   class Article < ActiveRecord::Base
 
98
      #     validates_presence_of :title, :message => :"title.blank"
 
99
      #   end
 
100
      #
 
101
      #   # config/locales/en.yml
 
102
      #   en:
 
103
      #     activerecord:
 
104
      #       errors:
 
105
      #         full_messages:
 
106
      #           title:
 
107
      #             blank: This title is screwed!
 
108
      def generate_full_message(options = {})
 
109
        keys = [
 
110
          :"full_messages.#{@message}",
 
111
          :'full_messages.format',
 
112
          '{{attribute}} {{message}}'
 
113
        ]
 
114
 
 
115
        options.merge!(:default => keys, :message => self.message)
 
116
        I18n.translate(keys.shift, options)
 
117
      end
 
118
 
 
119
      # Return user options with default options.
 
120
      #
 
121
      def default_options
 
122
        options.reverse_merge :scope => [:activerecord, :errors],
 
123
                              :model => @base.class.human_name,
 
124
                              :attribute => @base.class.human_attribute_name(attribute.to_s),
 
125
                              :value => value
 
126
      end
 
127
  end
 
128
 
 
129
  # Active Record validation is reported to and from this object, which is used by Base#save to
 
130
  # determine whether the object is in a valid state to be saved. See usage example in Validations.
 
131
  class Errors
 
132
    include Enumerable
 
133
 
 
134
    class << self
 
135
      def default_error_messages
 
136
        ActiveSupport::Deprecation.warn("ActiveRecord::Errors.default_error_messages has been deprecated. Please use I18n.translate('activerecord.errors.messages').")
 
137
        I18n.translate 'activerecord.errors.messages'
 
138
      end
 
139
    end
 
140
 
 
141
    def initialize(base) # :nodoc:
 
142
      @base = base
 
143
      clear
 
144
    end
 
145
 
 
146
    # Adds an error to the base object instead of any particular attribute. This is used
 
147
    # to report errors that don't tie to any specific attribute, but rather to the object
 
148
    # as a whole. These error messages don't get prepended with any field name when iterating
 
149
    # with +each_full+, so they should be complete sentences.
 
150
    def add_to_base(msg)
 
151
      add(:base, msg)
 
152
    end
 
153
 
 
154
    # Adds an error message (+messsage+) to the +attribute+, which will be returned on a call to <tt>on(attribute)</tt>
 
155
    # for the same attribute and ensure that this error object returns false when asked if <tt>empty?</tt>. More than one
 
156
    # error can be added to the same +attribute+ in which case an array will be returned on a call to <tt>on(attribute)</tt>.
 
157
    # If no +messsage+ is supplied, :invalid is assumed.
 
158
    # If +message+ is a Symbol, it will be translated, using the appropriate scope (see translate_error).
 
159
    #
 
160
    def add(attribute, message = nil, options = {})
 
161
      options[:message] = options.delete(:default) if options.has_key?(:default)
 
162
      error, message = message, nil if message.is_a?(Error)
 
163
 
 
164
      @errors[attribute.to_s] ||= []
 
165
      @errors[attribute.to_s] << (error || Error.new(@base, attribute, message, options))
 
166
    end
 
167
 
 
168
    # Will add an error message to each of the attributes in +attributes+ that is empty.
 
169
    def add_on_empty(attributes, custom_message = nil)
 
170
      for attr in [attributes].flatten
 
171
        value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s]
 
172
        is_empty = value.respond_to?(:empty?) ? value.empty? : false
 
173
        add(attr, :empty, :default => custom_message) unless !value.nil? && !is_empty
 
174
      end
 
175
    end
 
176
 
 
177
    # Will add an error message to each of the attributes in +attributes+ that is blank (using Object#blank?).
 
178
    def add_on_blank(attributes, custom_message = nil)
 
179
      for attr in [attributes].flatten
 
180
        value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s]
 
181
        add(attr, :blank, :default => custom_message) if value.blank?
 
182
      end
 
183
    end
 
184
 
 
185
    # Returns true if the specified +attribute+ has errors associated with it.
 
186
    #
 
187
    #   class Company < ActiveRecord::Base
 
188
    #     validates_presence_of :name, :address, :email
 
189
    #     validates_length_of :name, :in => 5..30
 
190
    #   end
 
191
    #
 
192
    #   company = Company.create(:address => '123 First St.')
 
193
    #   company.errors.invalid?(:name)      # => true
 
194
    #   company.errors.invalid?(:address)   # => false
 
195
    def invalid?(attribute)
 
196
      !@errors[attribute.to_s].nil?
 
197
    end
 
198
 
 
199
    # Returns +nil+, if no errors are associated with the specified +attribute+.
 
200
    # Returns the error message, if one error is associated with the specified +attribute+.
 
201
    # Returns an array of error messages, if more than one error is associated with the specified +attribute+.
 
202
    #
 
203
    #   class Company < ActiveRecord::Base
 
204
    #     validates_presence_of :name, :address, :email
 
205
    #     validates_length_of :name, :in => 5..30
 
206
    #   end
 
207
    #
 
208
    #   company = Company.create(:address => '123 First St.')
 
209
    #   company.errors.on(:name)      # => ["is too short (minimum is 5 characters)", "can't be blank"]
 
210
    #   company.errors.on(:email)     # => "can't be blank"
 
211
    #   company.errors.on(:address)   # => nil
 
212
    def on(attribute)
 
213
      attribute = attribute.to_s
 
214
      return nil unless @errors.has_key?(attribute)
 
215
      errors = @errors[attribute].map(&:to_s)
 
216
      errors.size == 1 ? errors.first : errors
 
217
    end
 
218
 
 
219
    alias :[] :on
 
220
 
 
221
    # Returns errors assigned to the base object through +add_to_base+ according to the normal rules of <tt>on(attribute)</tt>.
 
222
    def on_base
 
223
      on(:base)
 
224
    end
 
225
 
 
226
    # Yields each attribute and associated message per error added.
 
227
    #
 
228
    #   class Company < ActiveRecord::Base
 
229
    #     validates_presence_of :name, :address, :email
 
230
    #     validates_length_of :name, :in => 5..30
 
231
    #   end
 
232
    #
 
233
    #   company = Company.create(:address => '123 First St.')
 
234
    #   company.errors.each{|attr,msg| puts "#{attr} - #{msg}" }
 
235
    #   # => name - is too short (minimum is 5 characters)
 
236
    #   #    name - can't be blank
 
237
    #   #    address - can't be blank
 
238
    def each
 
239
      @errors.each_key { |attr| @errors[attr].each { |error| yield attr, error.message } }
 
240
    end
 
241
 
 
242
    def each_error
 
243
      @errors.each_key { |attr| @errors[attr].each { |error| yield attr, error } }
 
244
    end
 
245
 
 
246
    # Yields each full error message added. So <tt>Person.errors.add("first_name", "can't be empty")</tt> will be returned
 
247
    # through iteration as "First name can't be empty".
 
248
    #
 
249
    #   class Company < ActiveRecord::Base
 
250
    #     validates_presence_of :name, :address, :email
 
251
    #     validates_length_of :name, :in => 5..30
 
252
    #   end
 
253
    #
 
254
    #   company = Company.create(:address => '123 First St.')
 
255
    #   company.errors.each_full{|msg| puts msg }
 
256
    #   # => Name is too short (minimum is 5 characters)
 
257
    #   #    Name can't be blank
 
258
    #   #    Address can't be blank
 
259
    def each_full
 
260
      full_messages.each { |msg| yield msg }
 
261
    end
 
262
 
 
263
    # Returns all the full error messages in an array.
 
264
    #
 
265
    #   class Company < ActiveRecord::Base
 
266
    #     validates_presence_of :name, :address, :email
 
267
    #     validates_length_of :name, :in => 5..30
 
268
    #   end
 
269
    #
 
270
    #   company = Company.create(:address => '123 First St.')
 
271
    #   company.errors.full_messages # =>
 
272
    #     ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Address can't be blank"]
 
273
    def full_messages(options = {})
 
274
      @errors.values.inject([]) do |full_messages, errors|
 
275
        full_messages + errors.map { |error| error.full_message }
 
276
      end
 
277
    end
 
278
 
 
279
    # Returns true if no errors have been added.
 
280
    def empty?
 
281
      @errors.empty?
 
282
    end
 
283
 
 
284
    # Removes all errors that have been added.
 
285
    def clear
 
286
      @errors = ActiveSupport::OrderedHash.new
 
287
    end
 
288
 
 
289
    # Returns the total number of errors added. Two errors added to the same attribute will be counted as such.
 
290
    def size
 
291
      @errors.values.inject(0) { |error_count, attribute| error_count + attribute.size }
 
292
    end
 
293
 
 
294
    alias_method :count, :size
 
295
    alias_method :length, :size
 
296
 
 
297
    # Returns an XML representation of this error object.
 
298
    #
 
299
    #   class Company < ActiveRecord::Base
 
300
    #     validates_presence_of :name, :address, :email
 
301
    #     validates_length_of :name, :in => 5..30
 
302
    #   end
 
303
    #
 
304
    #   company = Company.create(:address => '123 First St.')
 
305
    #   company.errors.to_xml
 
306
    #   # =>  <?xml version="1.0" encoding="UTF-8"?>
 
307
    #   #     <errors>
 
308
    #   #       <error>Name is too short (minimum is 5 characters)</error>
 
309
    #   #       <error>Name can't be blank</error>
 
310
    #   #       <error>Address can't be blank</error>
 
311
    #   #     </errors>
 
312
    def to_xml(options={})
 
313
      options[:root] ||= "errors"
 
314
      options[:indent] ||= 2
 
315
      options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
 
316
 
 
317
      options[:builder].instruct! unless options.delete(:skip_instruct)
 
318
      options[:builder].errors do |e|
 
319
        full_messages.each { |msg| e.error(msg) }
 
320
      end
 
321
    end
 
322
 
 
323
    def generate_message(attribute, message = :invalid, options = {})
 
324
      ActiveSupport::Deprecation.warn("ActiveRecord::Errors#generate_message has been deprecated. Please use ActiveRecord::Error.new().to_s.")
 
325
      Error.new(@base, attribute, message, options).to_s
 
326
    end
 
327
  end
 
328
 
 
329
 
 
330
  # Please do have a look at ActiveRecord::Validations::ClassMethods for a higher level of validations.
 
331
  #
 
332
  # Active Records implement validation by overwriting Base#validate (or the variations, +validate_on_create+ and
 
333
  # +validate_on_update+). Each of these methods can inspect the state of the object, which usually means ensuring
 
334
  # that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).
 
335
  #
 
336
  # Example:
 
337
  #
 
338
  #   class Person < ActiveRecord::Base
 
339
  #     protected
 
340
  #       def validate
 
341
  #         errors.add_on_empty %w( first_name last_name )
 
342
  #         errors.add("phone_number", "has invalid format") unless phone_number =~ /[0-9]*/
 
343
  #       end
 
344
  #
 
345
  #       def validate_on_create # is only run the first time a new object is saved
 
346
  #         unless valid_discount?(membership_discount)
 
347
  #           errors.add("membership_discount", "has expired")
 
348
  #         end
 
349
  #       end
 
350
  #
 
351
  #       def validate_on_update
 
352
  #         errors.add_to_base("No changes have occurred") if unchanged_attributes?
 
353
  #       end
 
354
  #   end
 
355
  #
 
356
  #   person = Person.new("first_name" => "David", "phone_number" => "what?")
 
357
  #   person.save                         # => false (and doesn't do the save)
 
358
  #   person.errors.empty?                # => false
 
359
  #   person.errors.count                 # => 2
 
360
  #   person.errors.on "last_name"        # => "can't be empty"
 
361
  #   person.errors.on "phone_number"     # => "has invalid format"
 
362
  #   person.errors.each_full { |msg| puts msg }
 
363
  #                                       # => "Last name can't be empty\n" +
 
364
  #                                       #    "Phone number has invalid format"
 
365
  #
 
366
  #   person.attributes = { "last_name" => "Heinemeier", "phone_number" => "555-555" }
 
367
  #   person.save # => true (and person is now saved in the database)
 
368
  #
 
369
  # An Errors object is automatically created for every Active Record.
 
370
  module Validations
 
371
    VALIDATIONS = %w( validate validate_on_create validate_on_update )
 
372
 
 
373
    def self.included(base) # :nodoc:
 
374
      base.extend ClassMethods
 
375
      base.class_eval do
 
376
        alias_method_chain :save, :validation
 
377
        alias_method_chain :save!, :validation
 
378
      end
 
379
 
 
380
      base.send :include, ActiveSupport::Callbacks
 
381
      base.define_callbacks *VALIDATIONS
 
382
    end
 
383
 
 
384
    # Active Record classes can implement validations in several ways. The highest level, easiest to read,
 
385
    # and recommended approach is to use the declarative <tt>validates_..._of</tt> class methods (and
 
386
    # +validates_associated+) documented below. These are sufficient for most model validations.
 
387
    #
 
388
    # Slightly lower level is +validates_each+. It provides some of the same options as the purely declarative
 
389
    # validation methods, but like all the lower-level approaches it requires manually adding to the errors collection
 
390
    # when the record is invalid.
 
391
    #
 
392
    # At a yet lower level, a model can use the class methods +validate+, +validate_on_create+ and +validate_on_update+
 
393
    # to add validation methods or blocks. These are ActiveSupport::Callbacks and follow the same rules of inheritance
 
394
    # and chaining.
 
395
    #
 
396
    # The lowest level style is to define the instance methods +validate+, +validate_on_create+ and +validate_on_update+
 
397
    # as documented in ActiveRecord::Validations.
 
398
    #
 
399
    # == +validate+, +validate_on_create+ and +validate_on_update+ Class Methods
 
400
    #
 
401
    # Calls to these methods add a validation method or block to the class. Again, this approach is recommended
 
402
    # only when the higher-level methods documented below (<tt>validates_..._of</tt> and +validates_associated+) are
 
403
    # insufficient to handle the required validation.
 
404
    #
 
405
    # This can be done with a symbol pointing to a method:
 
406
    #
 
407
    #   class Comment < ActiveRecord::Base
 
408
    #     validate :must_be_friends
 
409
    #
 
410
    #     def must_be_friends
 
411
    #       errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
 
412
    #     end
 
413
    #   end
 
414
    #
 
415
    # Or with a block which is passed the current record to be validated:
 
416
    #
 
417
    #   class Comment < ActiveRecord::Base
 
418
    #     validate do |comment|
 
419
    #       comment.must_be_friends
 
420
    #     end
 
421
    #
 
422
    #     def must_be_friends
 
423
    #       errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
 
424
    #     end
 
425
    #   end
 
426
    #
 
427
    # This usage applies to +validate_on_create+ and +validate_on_update+ as well.
 
428
    module ClassMethods
 
429
      DEFAULT_VALIDATION_OPTIONS = {
 
430
        :on => :save,
 
431
        :allow_nil => false,
 
432
        :allow_blank => false,
 
433
        :message => nil
 
434
      }.freeze
 
435
 
 
436
      ALL_RANGE_OPTIONS = [ :is, :within, :in, :minimum, :maximum ].freeze
 
437
      ALL_NUMERICALITY_CHECKS = { :greater_than => '>', :greater_than_or_equal_to => '>=',
 
438
                                  :equal_to => '==', :less_than => '<', :less_than_or_equal_to => '<=',
 
439
                                  :odd => 'odd?', :even => 'even?' }.freeze
 
440
 
 
441
      # Validates each attribute against a block.
 
442
      #
 
443
      #   class Person < ActiveRecord::Base
 
444
      #     validates_each :first_name, :last_name do |record, attr, value|
 
445
      #       record.errors.add attr, 'starts with z.' if value[0] == ?z
 
446
      #     end
 
447
      #   end
 
448
      #
 
449
      # Options:
 
450
      # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
 
451
      # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
 
452
      # * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
 
453
      # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
 
454
      #   occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).  The
 
455
      #   method, proc or string should return or evaluate to a true or false value.
 
456
      # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
 
457
      #   not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).  The
 
458
      #   method, proc or string should return or evaluate to a true or false value.
 
459
      def validates_each(*attrs)
 
460
        options = attrs.extract_options!.symbolize_keys
 
461
        attrs   = attrs.flatten
 
462
 
 
463
        # Declare the validation.
 
464
        send(validation_method(options[:on] || :save), options) do |record|
 
465
          attrs.each do |attr|
 
466
            value = record.send(attr)
 
467
            next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
 
468
            yield record, attr, value
 
469
          end
 
470
        end
 
471
      end
 
472
 
 
473
      # Encapsulates the pattern of wanting to validate a password or email address field with a confirmation. Example:
 
474
      #
 
475
      #   Model:
 
476
      #     class Person < ActiveRecord::Base
 
477
      #       validates_confirmation_of :user_name, :password
 
478
      #       validates_confirmation_of :email_address, :message => "should match confirmation"
 
479
      #     end
 
480
      #
 
481
      #   View:
 
482
      #     <%= password_field "person", "password" %>
 
483
      #     <%= password_field "person", "password_confirmation" %>
 
484
      #
 
485
      # The added +password_confirmation+ attribute is virtual; it exists only as an in-memory attribute for validating the password.
 
486
      # To achieve this, the validation adds accessors to the model for the confirmation attribute. NOTE: This check is performed
 
487
      # only if +password_confirmation+ is not +nil+, and by default only on save. To require confirmation, make sure to add a presence
 
488
      # check for the confirmation attribute:
 
489
      #
 
490
      #   validates_presence_of :password_confirmation, :if => :password_changed?
 
491
      #
 
492
      # Configuration options:
 
493
      # * <tt>:message</tt> - A custom error message (default is: "doesn't match confirmation").
 
494
      # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
 
495
      # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
 
496
      #   occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).  The
 
497
      #   method, proc or string should return or evaluate to a true or false value.
 
498
      # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
 
499
      #   not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).  The
 
500
      #   method, proc or string should return or evaluate to a true or false value.
 
501
      def validates_confirmation_of(*attr_names)
 
502
        configuration = { :on => :save }
 
503
        configuration.update(attr_names.extract_options!)
 
504
 
 
505
        attr_accessor(*(attr_names.map { |n| "#{n}_confirmation" }))
 
506
 
 
507
        validates_each(attr_names, configuration) do |record, attr_name, value|
 
508
          unless record.send("#{attr_name}_confirmation").nil? or value == record.send("#{attr_name}_confirmation")
 
509
            record.errors.add(attr_name, :confirmation, :default => configuration[:message])
 
510
          end
 
511
        end
 
512
      end
 
513
 
 
514
      # Encapsulates the pattern of wanting to validate the acceptance of a terms of service check box (or similar agreement). Example:
 
515
      #
 
516
      #   class Person < ActiveRecord::Base
 
517
      #     validates_acceptance_of :terms_of_service
 
518
      #     validates_acceptance_of :eula, :message => "must be abided"
 
519
      #   end
 
520
      #
 
521
      # If the database column does not exist, the +terms_of_service+ attribute is entirely virtual. This check is
 
522
      # performed only if +terms_of_service+ is not +nil+ and by default on save.
 
523
      #
 
524
      # Configuration options:
 
525
      # * <tt>:message</tt> - A custom error message (default is: "must be accepted").
 
526
      # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
 
527
      # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is true).
 
528
      # * <tt>:accept</tt> - Specifies value that is considered accepted.  The default value is a string "1", which
 
529
      #   makes it easy to relate to an HTML checkbox. This should be set to +true+ if you are validating a database
 
530
      #   column, since the attribute is typecast from "1" to +true+ before validation.
 
531
      # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
 
532
      #   occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).  The
 
533
      #   method, proc or string should return or evaluate to a true or false value.
 
534
      # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
 
535
      #   not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).  The
 
536
      #   method, proc or string should return or evaluate to a true or false value.
 
537
      def validates_acceptance_of(*attr_names)
 
538
        configuration = { :on => :save, :allow_nil => true, :accept => "1" }
 
539
        configuration.update(attr_names.extract_options!)
 
540
 
 
541
        db_cols = begin
 
542
          column_names
 
543
        rescue Exception # To ignore both statement and connection errors
 
544
          []
 
545
        end
 
546
        names = attr_names.reject { |name| db_cols.include?(name.to_s) }
 
547
        attr_accessor(*names)
 
548
 
 
549
        validates_each(attr_names,configuration) do |record, attr_name, value|
 
550
          unless value == configuration[:accept]
 
551
            record.errors.add(attr_name, :accepted, :default => configuration[:message])
 
552
          end
 
553
        end
 
554
      end
 
555
 
 
556
      # Validates that the specified attributes are not blank (as defined by Object#blank?). Happens by default on save. Example:
 
557
      #
 
558
      #   class Person < ActiveRecord::Base
 
559
      #     validates_presence_of :first_name
 
560
      #   end
 
561
      #
 
562
      # The first_name attribute must be in the object and it cannot be blank.
 
563
      #
 
564
      # If you want to validate the presence of a boolean field (where the real values are true and false),
 
565
      # you will want to use <tt>validates_inclusion_of :field_name, :in => [true, false]</tt>.
 
566
      #
 
567
      # This is due to the way Object#blank? handles boolean values: <tt>false.blank? # => true</tt>.
 
568
      #
 
569
      # Configuration options:
 
570
      # * <tt>message</tt> - A custom error message (default is: "can't be blank").
 
571
      # * <tt>on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>,
 
572
      #   <tt>:update</tt>).
 
573
      # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
 
574
      #   occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).
 
575
      #   The method, proc or string should return or evaluate to a true or false value.
 
576
      # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
 
577
      #   not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).
 
578
      #   The method, proc or string should return or evaluate to a true or false value.
 
579
      #
 
580
      def validates_presence_of(*attr_names)
 
581
        configuration = { :on => :save }
 
582
        configuration.update(attr_names.extract_options!)
 
583
 
 
584
        # can't use validates_each here, because it cannot cope with nonexistent attributes,
 
585
        # while errors.add_on_empty can
 
586
        send(validation_method(configuration[:on]), configuration) do |record|
 
587
          record.errors.add_on_blank(attr_names, configuration[:message])
 
588
        end
 
589
      end
 
590
 
 
591
      # Validates that the specified attribute matches the length restrictions supplied. Only one option can be used at a time:
 
592
      #
 
593
      #   class Person < ActiveRecord::Base
 
594
      #     validates_length_of :first_name, :maximum=>30
 
595
      #     validates_length_of :last_name, :maximum=>30, :message=>"less than {{count}} if you don't mind"
 
596
      #     validates_length_of :fax, :in => 7..32, :allow_nil => true
 
597
      #     validates_length_of :phone, :in => 7..32, :allow_blank => true
 
598
      #     validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name"
 
599
      #     validates_length_of :fav_bra_size, :minimum => 1, :too_short => "please enter at least {{count}} character"
 
600
      #     validates_length_of :smurf_leader, :is => 4, :message => "papa is spelled with {{count}} characters... don't play me."
 
601
      #     validates_length_of :essay, :minimum => 100, :too_short => "Your essay must be at least {{count}} words."), :tokenizer => lambda {|str| str.scan(/\w+/) }
 
602
      #   end
 
603
      #
 
604
      # Configuration options:
 
605
      # * <tt>:minimum</tt> - The minimum size of the attribute.
 
606
      # * <tt>:maximum</tt> - The maximum size of the attribute.
 
607
      # * <tt>:is</tt> - The exact size of the attribute.
 
608
      # * <tt>:within</tt> - A range specifying the minimum and maximum size of the attribute.
 
609
      # * <tt>:in</tt> - A synonym(or alias) for <tt>:within</tt>.
 
610
      # * <tt>:allow_nil</tt> - Attribute may be +nil+; skip validation.
 
611
      # * <tt>:allow_blank</tt> - Attribute may be blank; skip validation.
 
612
      # * <tt>:too_long</tt> - The error message if the attribute goes over the maximum (default is: "is too long (maximum is {{count}} characters)").
 
613
      # * <tt>:too_short</tt> - The error message if the attribute goes under the minimum (default is: "is too short (min is {{count}} characters)").
 
614
      # * <tt>:wrong_length</tt> - The error message if using the <tt>:is</tt> method and the attribute is the wrong size (default is: "is the wrong length (should be {{count}} characters)").
 
615
      # * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>, <tt>:maximum</tt>, or <tt>:is</tt> violation.  An alias of the appropriate <tt>too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message.
 
616
      # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
 
617
      # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
 
618
      #   occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).  The
 
619
      #   method, proc or string should return or evaluate to a true or false value.
 
620
      # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
 
621
      #   not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).  The
 
622
      #   method, proc or string should return or evaluate to a true or false value.
 
623
      # * <tt>:tokenizer</tt> - Specifies how to split up the attribute string. (e.g. <tt>:tokenizer => lambda {|str| str.scan(/\w+/)}</tt> to
 
624
      #   count words as in above example.)
 
625
      #   Defaults to <tt>lambda{ |value| value.split(//) }</tt> which counts individual characters.
 
626
      def validates_length_of(*attrs)
 
627
        # Merge given options with defaults.
 
628
        options = {
 
629
          :tokenizer => lambda {|value| value.split(//)}
 
630
        }.merge(DEFAULT_VALIDATION_OPTIONS)
 
631
        options.update(attrs.extract_options!.symbolize_keys)
 
632
 
 
633
        # Ensure that one and only one range option is specified.
 
634
        range_options = ALL_RANGE_OPTIONS & options.keys
 
635
        case range_options.size
 
636
          when 0
 
637
            raise ArgumentError, 'Range unspecified.  Specify the :within, :maximum, :minimum, or :is option.'
 
638
          when 1
 
639
            # Valid number of options; do nothing.
 
640
          else
 
641
            raise ArgumentError, 'Too many range options specified.  Choose only one.'
 
642
        end
 
643
 
 
644
        # Get range option and value.
 
645
        option = range_options.first
 
646
        option_value = options[range_options.first]
 
647
        key = {:is => :wrong_length, :minimum => :too_short, :maximum => :too_long}[option]
 
648
        custom_message = options[:message] || options[key]
 
649
 
 
650
        case option
 
651
          when :within, :in
 
652
            raise ArgumentError, ":#{option} must be a Range" unless option_value.is_a?(Range)
 
653
 
 
654
            validates_each(attrs, options) do |record, attr, value|
 
655
              value = options[:tokenizer].call(value) if value.kind_of?(String)
 
656
              if value.nil? or value.size < option_value.begin
 
657
                record.errors.add(attr, :too_short, :default => custom_message || options[:too_short], :count => option_value.begin)
 
658
              elsif value.size > option_value.end
 
659
                record.errors.add(attr, :too_long, :default => custom_message || options[:too_long], :count => option_value.end)
 
660
              end
 
661
            end
 
662
          when :is, :minimum, :maximum
 
663
            raise ArgumentError, ":#{option} must be a nonnegative Integer" unless option_value.is_a?(Integer) and option_value >= 0
 
664
 
 
665
            # Declare different validations per option.
 
666
            validity_checks = { :is => "==", :minimum => ">=", :maximum => "<=" }
 
667
 
 
668
            validates_each(attrs, options) do |record, attr, value|
 
669
              value = options[:tokenizer].call(value) if value.kind_of?(String)
 
670
              unless !value.nil? and value.size.method(validity_checks[option])[option_value]
 
671
                record.errors.add(attr, key, :default => custom_message, :count => option_value)
 
672
              end
 
673
            end
 
674
        end
 
675
      end
 
676
 
 
677
      alias_method :validates_size_of, :validates_length_of
 
678
 
 
679
 
 
680
      # Validates whether the value of the specified attributes are unique across the system. Useful for making sure that only one user
 
681
      # can be named "davidhh".
 
682
      #
 
683
      #   class Person < ActiveRecord::Base
 
684
      #     validates_uniqueness_of :user_name, :scope => :account_id
 
685
      #   end
 
686
      #
 
687
      # It can also validate whether the value of the specified attributes are unique based on multiple scope parameters.  For example,
 
688
      # making sure that a teacher can only be on the schedule once per semester for a particular class.
 
689
      #
 
690
      #   class TeacherSchedule < ActiveRecord::Base
 
691
      #     validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
 
692
      #   end
 
693
      #
 
694
      # When the record is created, a check is performed to make sure that no record exists in the database with the given value for the specified
 
695
      # attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself.
 
696
      #
 
697
      # Configuration options:
 
698
      # * <tt>:message</tt> - Specifies a custom error message (default is: "has already been taken").
 
699
      # * <tt>:scope</tt> - One or more columns by which to limit the scope of the uniqueness constraint.
 
700
      # * <tt>:case_sensitive</tt> - Looks for an exact match. Ignored by non-text columns (+true+ by default).
 
701
      # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
 
702
      # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
 
703
      # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
 
704
      #   occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).  The
 
705
      #   method, proc or string should return or evaluate to a true or false value.
 
706
      # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
 
707
      #   not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).  The
 
708
      #   method, proc or string should return or evaluate to a true or false value.
 
709
      #
 
710
      # === Concurrency and integrity
 
711
      #
 
712
      # Using this validation method in conjunction with ActiveRecord::Base#save
 
713
      # does not guarantee the absence of duplicate record insertions, because
 
714
      # uniqueness checks on the application level are inherently prone to race
 
715
      # conditions. For example, suppose that two users try to post a Comment at
 
716
      # the same time, and a Comment's title must be unique. At the database-level,
 
717
      # the actions performed by these users could be interleaved in the following manner:
 
718
      #
 
719
      #               User 1                 |               User 2
 
720
      #  ------------------------------------+--------------------------------------
 
721
      #  # User 1 checks whether there's     |
 
722
      #  # already a comment with the title  |
 
723
      #  # 'My Post'. This is not the case.  |
 
724
      #  SELECT * FROM comments              |
 
725
      #  WHERE title = 'My Post'             |
 
726
      #                                      |
 
727
      #                                      | # User 2 does the same thing and also
 
728
      #                                      | # infers that his title is unique.
 
729
      #                                      | SELECT * FROM comments
 
730
      #                                      | WHERE title = 'My Post'
 
731
      #                                      |
 
732
      #  # User 1 inserts his comment.       |
 
733
      #  INSERT INTO comments                |
 
734
      #  (title, content) VALUES             |
 
735
      #  ('My Post', 'hi!')                  |
 
736
      #                                      |
 
737
      #                                      | # User 2 does the same thing.
 
738
      #                                      | INSERT INTO comments
 
739
      #                                      | (title, content) VALUES
 
740
      #                                      | ('My Post', 'hello!')
 
741
      #                                      |
 
742
      #                                      | # ^^^^^^
 
743
      #                                      | # Boom! We now have a duplicate
 
744
      #                                      | # title!
 
745
      #
 
746
      # This could even happen if you use transactions with the 'serializable'
 
747
      # isolation level. There are several ways to get around this problem:
 
748
      # - By locking the database table before validating, and unlocking it after
 
749
      #   saving. However, table locking is very expensive, and thus not
 
750
      #   recommended.
 
751
      # - By locking a lock file before validating, and unlocking it after saving.
 
752
      #   This does not work if you've scaled your Rails application across
 
753
      #   multiple web servers (because they cannot share lock files, or cannot
 
754
      #   do that efficiently), and thus not recommended.
 
755
      # - Creating a unique index on the field, by using
 
756
      #   ActiveRecord::ConnectionAdapters::SchemaStatements#add_index. In the
 
757
      #   rare case that a race condition occurs, the database will guarantee
 
758
      #   the field's uniqueness.
 
759
      #
 
760
      #   When the database catches such a duplicate insertion,
 
761
      #   ActiveRecord::Base#save will raise an ActiveRecord::StatementInvalid
 
762
      #   exception. You can either choose to let this error propagate (which
 
763
      #   will result in the default Rails exception page being shown), or you
 
764
      #   can catch it and restart the transaction (e.g. by telling the user
 
765
      #   that the title already exists, and asking him to re-enter the title).
 
766
      #   This technique is also known as optimistic concurrency control:
 
767
      #   http://en.wikipedia.org/wiki/Optimistic_concurrency_control
 
768
      #
 
769
      #   Active Record currently provides no way to distinguish unique
 
770
      #   index constraint errors from other types of database errors, so you
 
771
      #   will have to parse the (database-specific) exception message to detect
 
772
      #   such a case.
 
773
      def validates_uniqueness_of(*attr_names)
 
774
        configuration = { :case_sensitive => true }
 
775
        configuration.update(attr_names.extract_options!)
 
776
 
 
777
        validates_each(attr_names,configuration) do |record, attr_name, value|
 
778
          # The check for an existing value should be run from a class that
 
779
          # isn't abstract. This means working down from the current class
 
780
          # (self), to the first non-abstract class. Since classes don't know
 
781
          # their subclasses, we have to build the hierarchy between self and
 
782
          # the record's class.
 
783
          class_hierarchy = [record.class]
 
784
          while class_hierarchy.first != self
 
785
            class_hierarchy.insert(0, class_hierarchy.first.superclass)
 
786
          end
 
787
 
 
788
          # Now we can work our way down the tree to the first non-abstract
 
789
          # class (which has a database table to query from).
 
790
          finder_class = class_hierarchy.detect { |klass| !klass.abstract_class? }
 
791
 
 
792
          column = finder_class.columns_hash[attr_name.to_s]
 
793
 
 
794
          if value.nil?
 
795
            comparison_operator = "IS ?"
 
796
          elsif column.text?
 
797
            comparison_operator = "#{connection.case_sensitive_equality_operator} ?"
 
798
            value = column.limit ? value.to_s.mb_chars[0, column.limit] : value.to_s
 
799
          else
 
800
            comparison_operator = "= ?"
 
801
          end
 
802
 
 
803
          sql_attribute = "#{record.class.quoted_table_name}.#{connection.quote_column_name(attr_name)}"
 
804
 
 
805
          if value.nil? || (configuration[:case_sensitive] || !column.text?)
 
806
            condition_sql = "#{sql_attribute} #{comparison_operator}"
 
807
            condition_params = [value]
 
808
          else
 
809
            condition_sql = "LOWER(#{sql_attribute}) #{comparison_operator}"
 
810
            condition_params = [value.mb_chars.downcase]
 
811
          end
 
812
 
 
813
          if scope = configuration[:scope]
 
814
            Array(scope).map do |scope_item|
 
815
              scope_value = record.send(scope_item)
 
816
              condition_sql << " AND " << attribute_condition("#{record.class.quoted_table_name}.#{scope_item}", scope_value)
 
817
              condition_params << scope_value
 
818
            end
 
819
          end
 
820
 
 
821
          unless record.new_record?
 
822
            condition_sql << " AND #{record.class.quoted_table_name}.#{record.class.primary_key} <> ?"
 
823
            condition_params << record.send(:id)
 
824
          end
 
825
 
 
826
          finder_class.with_exclusive_scope do
 
827
            if finder_class.exists?([condition_sql, *condition_params])
 
828
              record.errors.add(attr_name, :taken, :default => configuration[:message], :value => value)
 
829
            end
 
830
          end
 
831
        end
 
832
      end
 
833
 
 
834
 
 
835
      # Validates whether the value of the specified attribute is of the correct form by matching it against the regular expression
 
836
      # provided.
 
837
      #
 
838
      #   class Person < ActiveRecord::Base
 
839
      #     validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
 
840
      #   end
 
841
      #
 
842
      # Note: use <tt>\A</tt> and <tt>\Z</tt> to match the start and end of the string, <tt>^</tt> and <tt>$</tt> match the start/end of a line.
 
843
      #
 
844
      # A regular expression must be provided or else an exception will be raised.
 
845
      #
 
846
      # Configuration options:
 
847
      # * <tt>:message</tt> - A custom error message (default is: "is invalid").
 
848
      # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
 
849
      # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
 
850
      # * <tt>:with</tt> - The regular expression used to validate the format with (note: must be supplied!).
 
851
      # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
 
852
      # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
 
853
      #   occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).  The
 
854
      #   method, proc or string should return or evaluate to a true or false value.
 
855
      # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
 
856
      #   not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).  The
 
857
      #   method, proc or string should return or evaluate to a true or false value.
 
858
      def validates_format_of(*attr_names)
 
859
        configuration = { :on => :save, :with => nil }
 
860
        configuration.update(attr_names.extract_options!)
 
861
 
 
862
        raise(ArgumentError, "A regular expression must be supplied as the :with option of the configuration hash") unless configuration[:with].is_a?(Regexp)
 
863
 
 
864
        validates_each(attr_names, configuration) do |record, attr_name, value|
 
865
          unless value.to_s =~ configuration[:with]
 
866
            record.errors.add(attr_name, :invalid, :default => configuration[:message], :value => value)
 
867
          end
 
868
        end
 
869
      end
 
870
 
 
871
      # Validates whether the value of the specified attribute is available in a particular enumerable object.
 
872
      #
 
873
      #   class Person < ActiveRecord::Base
 
874
      #     validates_inclusion_of :gender, :in => %w( m f )
 
875
      #     validates_inclusion_of :age, :in => 0..99
 
876
      #     validates_inclusion_of :format, :in => %w( jpg gif png ), :message => "extension {{value}} is not included in the list"
 
877
      #   end
 
878
      #
 
879
      # Configuration options:
 
880
      # * <tt>:in</tt> - An enumerable object of available items.
 
881
      # * <tt>:message</tt> - Specifies a custom error message (default is: "is not included in the list").
 
882
      # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
 
883
      # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
 
884
      # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
 
885
      #   occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).  The
 
886
      #   method, proc or string should return or evaluate to a true or false value.
 
887
      # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
 
888
      #   not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).  The
 
889
      #   method, proc or string should return or evaluate to a true or false value.
 
890
      def validates_inclusion_of(*attr_names)
 
891
        configuration = { :on => :save }
 
892
        configuration.update(attr_names.extract_options!)
 
893
 
 
894
        enum = configuration[:in] || configuration[:within]
 
895
 
 
896
        raise(ArgumentError, "An object with the method include? is required must be supplied as the :in option of the configuration hash") unless enum.respond_to?(:include?)
 
897
 
 
898
        validates_each(attr_names, configuration) do |record, attr_name, value|
 
899
          unless enum.include?(value)
 
900
            record.errors.add(attr_name, :inclusion, :default => configuration[:message], :value => value)
 
901
          end
 
902
        end
 
903
      end
 
904
 
 
905
      # Validates that the value of the specified attribute is not in a particular enumerable object.
 
906
      #
 
907
      #   class Person < ActiveRecord::Base
 
908
      #     validates_exclusion_of :username, :in => %w( admin superuser ), :message => "You don't belong here"
 
909
      #     validates_exclusion_of :age, :in => 30..60, :message => "This site is only for under 30 and over 60"
 
910
      #     validates_exclusion_of :format, :in => %w( mov avi ), :message => "extension {{value}} is not allowed"
 
911
      #   end
 
912
      #
 
913
      # Configuration options:
 
914
      # * <tt>:in</tt> - An enumerable object of items that the value shouldn't be part of.
 
915
      # * <tt>:message</tt> - Specifies a custom error message (default is: "is reserved").
 
916
      # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
 
917
      # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
 
918
      # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
 
919
      #   occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).  The
 
920
      #   method, proc or string should return or evaluate to a true or false value.
 
921
      # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
 
922
      #   not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).  The
 
923
      #   method, proc or string should return or evaluate to a true or false value.
 
924
      def validates_exclusion_of(*attr_names)
 
925
        configuration = { :on => :save }
 
926
        configuration.update(attr_names.extract_options!)
 
927
 
 
928
        enum = configuration[:in] || configuration[:within]
 
929
 
 
930
        raise(ArgumentError, "An object with the method include? is required must be supplied as the :in option of the configuration hash") unless enum.respond_to?(:include?)
 
931
 
 
932
        validates_each(attr_names, configuration) do |record, attr_name, value|
 
933
          if enum.include?(value)
 
934
            record.errors.add(attr_name, :exclusion, :default => configuration[:message], :value => value)
 
935
          end
 
936
        end
 
937
      end
 
938
 
 
939
      # Validates whether the associated object or objects are all valid themselves. Works with any kind of association.
 
940
      #
 
941
      #   class Book < ActiveRecord::Base
 
942
      #     has_many :pages
 
943
      #     belongs_to :library
 
944
      #
 
945
      #     validates_associated :pages, :library
 
946
      #   end
 
947
      #
 
948
      # Warning: If, after the above definition, you then wrote:
 
949
      #
 
950
      #   class Page < ActiveRecord::Base
 
951
      #     belongs_to :book
 
952
      #
 
953
      #     validates_associated :book
 
954
      #   end
 
955
      #
 
956
      # this would specify a circular dependency and cause infinite recursion.
 
957
      #
 
958
      # NOTE: This validation will not fail if the association hasn't been assigned. If you want to ensure that the association
 
959
      # is both present and guaranteed to be valid, you also need to use +validates_presence_of+.
 
960
      #
 
961
      # Configuration options:
 
962
      # * <tt>:message</tt> - A custom error message (default is: "is invalid")
 
963
      # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
 
964
      # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
 
965
      #   occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).  The
 
966
      #   method, proc or string should return or evaluate to a true or false value.
 
967
      # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
 
968
      #   not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).  The
 
969
      #   method, proc or string should return or evaluate to a true or false value.
 
970
      def validates_associated(*attr_names)
 
971
        configuration = { :on => :save }
 
972
        configuration.update(attr_names.extract_options!)
 
973
 
 
974
        validates_each(attr_names, configuration) do |record, attr_name, value|
 
975
          unless (value.is_a?(Array) ? value : [value]).collect { |r| r.nil? || r.valid? }.all?
 
976
            record.errors.add(attr_name, :invalid, :default => configuration[:message], :value => value)
 
977
          end
 
978
        end
 
979
      end
 
980
 
 
981
      # Validates whether the value of the specified attribute is numeric by trying to convert it to
 
982
      # a float with Kernel.Float (if <tt>only_integer</tt> is false) or applying it to the regular expression
 
983
      # <tt>/\A[\+\-]?\d+\Z/</tt> (if <tt>only_integer</tt> is set to true).
 
984
      #
 
985
      #   class Person < ActiveRecord::Base
 
986
      #     validates_numericality_of :value, :on => :create
 
987
      #   end
 
988
      #
 
989
      # Configuration options:
 
990
      # * <tt>:message</tt> - A custom error message (default is: "is not a number").
 
991
      # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
 
992
      # * <tt>:only_integer</tt> - Specifies whether the value has to be an integer, e.g. an integral value (default is +false+).
 
993
      # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is +false+). Notice that for fixnum and float columns empty strings are converted to +nil+.
 
994
      # * <tt>:greater_than</tt> - Specifies the value must be greater than the supplied value.
 
995
      # * <tt>:greater_than_or_equal_to</tt> - Specifies the value must be greater than or equal the supplied value.
 
996
      # * <tt>:equal_to</tt> - Specifies the value must be equal to the supplied value.
 
997
      # * <tt>:less_than</tt> - Specifies the value must be less than the supplied value.
 
998
      # * <tt>:less_than_or_equal_to</tt> - Specifies the value must be less than or equal the supplied value.
 
999
      # * <tt>:odd</tt> - Specifies the value must be an odd number.
 
1000
      # * <tt>:even</tt> - Specifies the value must be an even number.
 
1001
      # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
 
1002
      #   occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).  The
 
1003
      #   method, proc or string should return or evaluate to a true or false value.
 
1004
      # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
 
1005
      #   not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).  The
 
1006
      #   method, proc or string should return or evaluate to a true or false value.
 
1007
      def validates_numericality_of(*attr_names)
 
1008
        configuration = { :on => :save, :only_integer => false, :allow_nil => false }
 
1009
        configuration.update(attr_names.extract_options!)
 
1010
 
 
1011
 
 
1012
        numericality_options = ALL_NUMERICALITY_CHECKS.keys & configuration.keys
 
1013
 
 
1014
        (numericality_options - [ :odd, :even ]).each do |option|
 
1015
          raise ArgumentError, ":#{option} must be a number" unless configuration[option].is_a?(Numeric)
 
1016
        end
 
1017
 
 
1018
        validates_each(attr_names,configuration) do |record, attr_name, value|
 
1019
          raw_value = record.send("#{attr_name}_before_type_cast") || value
 
1020
 
 
1021
          next if configuration[:allow_nil] and raw_value.nil?
 
1022
 
 
1023
          if configuration[:only_integer]
 
1024
            unless raw_value.to_s =~ /\A[+-]?\d+\Z/
 
1025
              record.errors.add(attr_name, :not_a_number, :value => raw_value, :default => configuration[:message])
 
1026
              next
 
1027
            end
 
1028
            raw_value = raw_value.to_i
 
1029
          else
 
1030
            begin
 
1031
              raw_value = Kernel.Float(raw_value)
 
1032
            rescue ArgumentError, TypeError
 
1033
              record.errors.add(attr_name, :not_a_number, :value => raw_value, :default => configuration[:message])
 
1034
              next
 
1035
            end
 
1036
          end
 
1037
 
 
1038
          numericality_options.each do |option|
 
1039
            case option
 
1040
              when :odd, :even
 
1041
                unless raw_value.to_i.method(ALL_NUMERICALITY_CHECKS[option])[]
 
1042
                  record.errors.add(attr_name, option, :value => raw_value, :default => configuration[:message])
 
1043
                end
 
1044
              else
 
1045
                record.errors.add(attr_name, option, :default => configuration[:message], :value => raw_value, :count => configuration[option]) unless raw_value.method(ALL_NUMERICALITY_CHECKS[option])[configuration[option]]
 
1046
            end
 
1047
          end
 
1048
        end
 
1049
      end
 
1050
 
 
1051
      # Creates an object just like Base.create but calls save! instead of save
 
1052
      # so an exception is raised if the record is invalid.
 
1053
      def create!(attributes = nil, &block)
 
1054
        if attributes.is_a?(Array)
 
1055
          attributes.collect { |attr| create!(attr, &block) }
 
1056
        else
 
1057
          object = new(attributes)
 
1058
          yield(object) if block_given?
 
1059
          object.save!
 
1060
          object
 
1061
        end
 
1062
      end
 
1063
 
 
1064
      private
 
1065
        def validation_method(on)
 
1066
          case on
 
1067
            when :save   then :validate
 
1068
            when :create then :validate_on_create
 
1069
            when :update then :validate_on_update
 
1070
          end
 
1071
        end
 
1072
    end
 
1073
 
 
1074
    # The validation process on save can be skipped by passing false. The regular Base#save method is
 
1075
    # replaced with this when the validations module is mixed in, which it is by default.
 
1076
    def save_with_validation(perform_validation = true)
 
1077
      if perform_validation && valid? || !perform_validation
 
1078
        save_without_validation
 
1079
      else
 
1080
        false
 
1081
      end
 
1082
    end
 
1083
 
 
1084
    # Attempts to save the record just like Base#save but will raise a RecordInvalid exception instead of returning false
 
1085
    # if the record is not valid.
 
1086
    def save_with_validation!
 
1087
      if valid?
 
1088
        save_without_validation!
 
1089
      else
 
1090
        raise RecordInvalid.new(self)
 
1091
      end
 
1092
    end
 
1093
 
 
1094
    # Runs +validate+ and +validate_on_create+ or +validate_on_update+ and returns true if no errors were added otherwise false.
 
1095
    def valid?
 
1096
      errors.clear
 
1097
 
 
1098
      run_callbacks(:validate)
 
1099
      validate
 
1100
 
 
1101
      if new_record?
 
1102
        run_callbacks(:validate_on_create)
 
1103
        validate_on_create
 
1104
      else
 
1105
        run_callbacks(:validate_on_update)
 
1106
        validate_on_update
 
1107
      end
 
1108
 
 
1109
      errors.empty?
 
1110
    end
 
1111
 
 
1112
    # Performs the opposite of <tt>valid?</tt>. Returns true if errors were added, false otherwise.
 
1113
    def invalid?
 
1114
      !valid?
 
1115
    end
 
1116
 
 
1117
    # Returns the Errors object that holds all information about attribute error messages.
 
1118
    def errors
 
1119
      @errors ||= Errors.new(self)
 
1120
    end
 
1121
 
 
1122
    protected
 
1123
      # Overwrite this method for validation checks on all saves and use <tt>Errors.add(field, msg)</tt> for invalid attributes.
 
1124
      def validate
 
1125
      end
 
1126
 
 
1127
      # Overwrite this method for validation checks used only on creation.
 
1128
      def validate_on_create
 
1129
      end
 
1130
 
 
1131
      # Overwrite this method for validation checks used only on updates.
 
1132
      def validate_on_update
 
1133
      end
 
1134
  end
 
1135
end