2008-03-31 20:05:48 -04:00
module ActiveModel
module Validations
module ClassMethods
# Validates whether the value of the specified attribute is available in a particular enumerable object.
#
# class Person < ActiveRecord::Base
2009-03-16 07:28:36 -04:00
# validates_inclusion_of :gender, :in => %w( m f )
2008-03-31 20:05:48 -04:00
# validates_inclusion_of :age, :in => 0..99
2009-03-19 19:28:59 -04:00
# validates_inclusion_of :format, :in => %w( jpg gif png ), :message => "extension {{value}} is not included in the list"
2008-03-31 20:05:48 -04:00
# end
#
# Configuration options:
2009-03-19 19:28:59 -04:00
# * <tt>:in</tt> - An enumerable object of available items.
# * <tt>:message</tt> - Specifies a custom error message (default is: "is not included in the list").
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
2008-05-02 09:45:23 -04:00
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
2008-03-31 20:05:48 -04:00
# method, proc or string should return or evaluate to a true or false value.
2008-05-02 09:45:23 -04:00
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
2008-03-31 20:05:48 -04:00
# method, proc or string should return or evaluate to a true or false value.
def validates_inclusion_of ( * attr_names )
2009-03-19 19:28:59 -04:00
configuration = { :on = > :save }
2008-03-31 20:05:48 -04:00
configuration . update ( attr_names . extract_options! )
enum = configuration [ :in ] || configuration [ :within ]
2008-09-02 04:04:53 -04:00
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? )
2008-03-31 20:05:48 -04:00
validates_each ( attr_names , configuration ) do | record , attr_name , value |
2009-03-19 19:28:59 -04:00
unless enum . include? ( value )
record . errors . add ( attr_name , :inclusion , :default = > configuration [ :message ] , :value = > value )
end
2008-03-31 20:05:48 -04:00
end
end
end
end
end