aboutsummaryrefslogtreecommitdiffstats
path: root/activemodel/lib/active_model
diff options
context:
space:
mode:
Diffstat (limited to 'activemodel/lib/active_model')
-rw-r--r--activemodel/lib/active_model/validations/inclusion.rb32
1 files changed, 12 insertions, 20 deletions
diff --git a/activemodel/lib/active_model/validations/inclusion.rb b/activemodel/lib/active_model/validations/inclusion.rb
index 7d4ccc0d4f..92ac940f36 100644
--- a/activemodel/lib/active_model/validations/inclusion.rb
+++ b/activemodel/lib/active_model/validations/inclusion.rb
@@ -1,3 +1,5 @@
+require 'active_support/core_ext/range.rb'
+
module ActiveModel
# == Active Model Inclusion Validator
@@ -8,27 +10,15 @@ module ActiveModel
":in option of the configuration hash" unless options[:in].respond_to?(:include?)
end
- # On Ruby 1.9 Range#include? checks all possible values in the range for equality,
- # so it may be slow for large ranges. The new Range#cover? uses the previous logic
- # of comparing a value with the range endpoints.
- if (1..2).respond_to?(:cover?)
- def validate_each(record, attribute, value)
- included = if options[:in].is_a?(Range)
- options[:in].cover?(value)
- else
- options[:in].include?(value)
- end
+ def validate_each(record, attribute, value)
+ record.errors.add(attribute, :inclusion, options.except(:in).merge!(:value => value)) unless options[:in].send(include?, value)
+ end
- unless included
- record.errors.add(attribute, :inclusion, options.except(:in).merge!(:value => value))
- end
- end
- else
- def validate_each(record, attribute, value)
- unless options[:in].include?(value)
- record.errors.add(attribute, :inclusion, options.except(:in).merge!(:value => value))
- end
- end
+ # In Ruby 1.9 <tt>Range#include?</tt> on non-numeric ranges checks all possible values in the
+ # range for equality, so it may be slow for large ranges. The new <tt>Range#cover?</tt>
+ # uses the previous logic of comparing a value with the range endpoints.
+ def include?
+ options[:in].is_a?(Range) ? :cover? : :include?
end
end
@@ -43,6 +33,8 @@ module ActiveModel
#
# Configuration options:
# * <tt>:in</tt> - An enumerable object of available items.
+ # If the enumerable is a range the test is performed with <tt>Range#cover?</tt>
+ # (backported in Active Support for 1.8), otherwise with <tt>include?</tt>.
# * <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+).