Permalink
Browse files

Merge pull request #10774 from chuckbergeron/validates-inclusion-of-a…

…ccuracy-for-non-numeric-ranges

Greater accuracy for validates_inclusion_of on non-numeric ranges

Closes #10774, fixes #10593
  • Loading branch information...
2 parents a1fedfa + 0317b93 commit 61346d1b42527d072c0b4bd97f3b5ce3f6be214c @carlosantoniodasilva carlosantoniodasilva committed Jun 26, 2013
View
@@ -1,3 +1,12 @@
+* `inclusion` / `exclusion` validations with ranges will only use the faster
+ `Range#cover` for numerical ranges, and the more accurate `Range#include?`
+ for non-numerical ones.
+
+ Fixes range validations like `:a..:f` that used to pass with values like `:be`.
+ Fixes #10593
+
+ *Charles Bergeron*
+
* Fix regression in has_secure_password. When a password is set, but a
confirmation is an empty string, it would incorrectly save.
@@ -31,10 +31,11 @@ def delimiter
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.
+ # range for equality, which is slower but more accurate. <tt>Range#cover?</tt> uses
+ # the previous logic of comparing a value with the range endpoints, which is fast
+ # but is only accurate on numeric ranges.
def inclusion_method(enumerable)
- enumerable.is_a?(Range) ? :cover? : :include?
+ (enumerable.is_a?(Range) && enumerable.first.is_a?(Numeric)) ? :cover? : :include?
end
end
end
@@ -28,7 +28,7 @@ module HelperMethods
# Configuration options:
# * <tt>:in</tt> - An enumerable object of available items. This can be
# supplied as a proc, lambda or symbol which returns an enumerable. If the
- # enumerable is a range the test is performed with <tt>Range#cover?</tt>,
+ # enumerable is a numerical range the test is performed with <tt>Range#cover?</tt>,
# otherwise with <tt>include?</tt>.
# * <tt>:within</tt> - A synonym(or alias) for <tt>:in</tt>
# * <tt>:message</tt> - Specifies a custom error message (default is: "is
@@ -14,6 +14,7 @@ def test_validates_inclusion_of_range
Topic.validates_inclusion_of(:title, in: 'aaa'..'bbb')
assert Topic.new("title" => "bbc", "content" => "abc").invalid?
assert Topic.new("title" => "aa", "content" => "abc").invalid?
+ assert Topic.new("title" => "aaab", "content" => "abc").invalid?
assert Topic.new("title" => "aaa", "content" => "abc").valid?
assert Topic.new("title" => "abc", "content" => "abc").valid?
assert Topic.new("title" => "bbb", "content" => "abc").valid?

0 comments on commit 61346d1

Please sign in to comment.