Skip to content
This repository
Browse code

Change validates inclusion to use cover? for Ranges in ruby 1.9 [#6453

…state:committed]

Signed-off-by: Xavier Noria <fxn@hashref.com>
  • Loading branch information...
commit d7b539aae2dec5835d59d9d7373c96d2ec8f662d 1 parent ff5db18
Frederick Cheung authored February 18, 2011 fxn committed February 18, 2011
23  activemodel/lib/active_model/validations/inclusion.rb
@@ -8,9 +8,26 @@ def check_validity!
8 8
                               ":in option of the configuration hash" unless options[:in].respond_to?(:include?)
9 9
       end
10 10
 
11  
-      def validate_each(record, attribute, value)
12  
-        unless options[:in].include?(value)
13  
-          record.errors.add(attribute, :inclusion, options.except(:in).merge!(:value => value))
  11
+      # On Ruby 1.9 Range#include? checks all possible values in the range for equality,
  12
+      # so it may be slow for large ranges. The new Range#cover? uses the previous logic
  13
+      # of comparing a value with the range endpoints.
  14
+      if (1..2).respond_to?(:cover?)
  15
+        def validate_each(record, attribute, value)
  16
+          included = if options[:in].is_a?(Range)
  17
+            options[:in].cover?(value)
  18
+          else
  19
+            options[:in].include?(value)
  20
+          end
  21
+
  22
+          unless included
  23
+            record.errors.add(attribute, :inclusion, options.except(:in).merge!(:value => value))
  24
+          end
  25
+        end
  26
+      else
  27
+        def validate_each(record, attribute, value)
  28
+          unless options[:in].include?(value)
  29
+            record.errors.add(attribute, :inclusion, options.except(:in).merge!(:value => value))
  30
+          end
14 31
         end
15 32
       end
16 33
     end
9  activemodel/test/cases/validations/inclusion_validation_test.rb
@@ -10,6 +10,15 @@ def teardown
10 10
     Topic.reset_callbacks(:validate)
11 11
   end
12 12
 
  13
+  def test_validates_inclusion_of_range
  14
+    Topic.validates_inclusion_of( :title, :in => 'aaa'..'bbb' )
  15
+    assert Topic.new("title" => "bbc", "content" => "abc").invalid?
  16
+    assert Topic.new("title" => "aa", "content" => "abc").invalid?
  17
+    assert Topic.new("title" => "aaa", "content" => "abc").valid?
  18
+    assert Topic.new("title" => "abc", "content" => "abc").valid?
  19
+    assert Topic.new("title" => "bbb", "content" => "abc").valid?
  20
+  end
  21
+
13 22
   def test_validates_inclusion_of
14 23
     Topic.validates_inclusion_of( :title, :in => %w( a b c d e f g ) )
15 24
 

0 notes on commit d7b539a

Please sign in to comment.
Something went wrong with that request. Please try again.