aboutsummaryrefslogtreecommitdiffstats
path: root/activemodel/lib/active_model/validations/clusivity.rb
blob: 643a6f2b7cff55c05a3aaf0f56410864a588bde3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
require 'active_support/core_ext/range.rb'

module ActiveModel
  module Validations
    module Clusivity #:nodoc:
      ERROR_MESSAGE = "An object with the method #include? or a proc or lambda is required, " <<
                      "and must be supplied as the :in (or :within) option of the configuration hash"

      def check_validity!
        unless [:include?, :call].any?{ |method| delimiter.respond_to?(method) }
          raise ArgumentError, ERROR_MESSAGE
        end
      end

    private

      def include?(record, value)
        exclusions = delimiter.respond_to?(:call) ? delimiter.call(record) : delimiter
        exclusions.send(inclusion_method(exclusions), value)
      end

      def delimiter
        @delimiter ||= options[:in] || options[:within]
      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