aboutsummaryrefslogtreecommitdiffstats
path: root/activemodel/lib/active_model/validations/clusivity.rb
diff options
context:
space:
mode:
authorSantiago Pastorino <santiago@wyeworks.com>2012-03-28 15:13:29 -0700
committerSantiago Pastorino <santiago@wyeworks.com>2012-03-28 15:13:29 -0700
commitddaeb4b6cf6c1a1779c6e46ff49e8c5f5e0b7418 (patch)
tree724e5beb7403020f44f53d14444f29f0c190530d /activemodel/lib/active_model/validations/clusivity.rb
parentf0268d56afa6be2eb4eb1fb953821d241f5adfc9 (diff)
parent170956cdae043733288c2dc1440b8940af309793 (diff)
downloadrails-ddaeb4b6cf6c1a1779c6e46ff49e8c5f5e0b7418.tar.gz
rails-ddaeb4b6cf6c1a1779c6e46ff49e8c5f5e0b7418.tar.bz2
rails-ddaeb4b6cf6c1a1779c6e46ff49e8c5f5e0b7418.zip
Merge pull request #5643 from rafaelfranca/remove-duplication
Remove code duplication in InclusionValidator and ExclusionValidator.
Diffstat (limited to 'activemodel/lib/active_model/validations/clusivity.rb')
-rw-r--r--activemodel/lib/active_model/validations/clusivity.rb31
1 files changed, 31 insertions, 0 deletions
diff --git a/activemodel/lib/active_model/validations/clusivity.rb b/activemodel/lib/active_model/validations/clusivity.rb
new file mode 100644
index 0000000000..b632a2bd6b
--- /dev/null
+++ b/activemodel/lib/active_model/validations/clusivity.rb
@@ -0,0 +1,31 @@
+require 'active_support/core_ext/range.rb'
+
+module ActiveModel
+ module Validations
+ module Clusivity
+ ERROR_MESSAGE = "An object with the method #include? or a proc or lambda is required, " <<
+ "and must be supplied as the :in option of the configuration hash"
+
+ def check_validity!
+ unless [:include?, :call].any?{ |method| options[:in].respond_to?(method) }
+ raise ArgumentError, ERROR_MESSAGE
+ end
+ end
+
+ private
+
+ def include?(record, value)
+ delimiter = options[:in]
+ exclusions = delimiter.respond_to?(:call) ? delimiter.call(record) : delimiter
+ exclusions.send(inclusion_method(exclusions), value)
+ 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 inclusion_method(enumerable)
+ enumerable.is_a?(Range) ? :cover? : :include?
+ end
+ end
+ end
+end