aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/relation/predicate_builder/array_handler.rb
blob: 78dba8be061b23ecba9f8ee7286447f6aefc9658 (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
module ActiveRecord
  class PredicateBuilder
    class ArrayHandler # :nodoc:
      def call(attribute, value)
        return attribute.in([]) if value.empty?

        values = value.map { |x| x.is_a?(Base) ? x.id : x }
        ranges, values = values.partition { |v| v.is_a?(Range) }
        nils, values = values.partition(&:nil?)

        values_predicate =
          case values.length
          when 0 then NullPredicate
          when 1 then attribute.eq(values.first)
          else attribute.in(values)
          end

        unless nils.empty?
          values_predicate = values_predicate.or(attribute.eq(nil))
        end

        array_predicates = ranges.map { |range| attribute.in(range) }
        array_predicates << values_predicate
        array_predicates.inject { |composite, predicate| composite.or(predicate) }
      end

      module NullPredicate
        def self.or(other)
          other
        end
      end
    end
  end
end