aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/relation/predicate_builder/array_handler.rb
blob: 2f6c34ac082c14d8df96d6d786ec098455785b84 (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
module ActiveRecord
  class PredicateBuilder
    class ArrayHandler # :nodoc:
      def call(attribute, value)
        values = value.map { |x| x.is_a?(Base) ? x.id : x }
        ranges, values = values.partition { |v| v.is_a?(Range) }

        values_predicate = if values.include?(nil)
          values = values.compact

          case values.length
          when 0
            attribute.eq(nil)
          when 1
            attribute.eq(values.first).or(attribute.eq(nil))
          else
            attribute.in(values).or(attribute.eq(nil))
          end
        else
          attribute.in(values)
        end

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