Class: ActiveRecord::PredicateBuilder::ArrayHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record/relation/predicate_builder/array_handler.rb

Overview

:nodoc:

Defined Under Namespace

Modules: NullPredicate

Instance Method Summary collapse

Constructor Details

#initialize(predicate_builder) ⇒ ArrayHandler

Returns a new instance of ArrayHandler.



6
7
8
# File 'lib/active_record/relation/predicate_builder/array_handler.rb', line 6

def initialize(predicate_builder)
  @predicate_builder = predicate_builder
end

Instance Method Details

#call(attribute, value) ⇒ Object



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
35
# File 'lib/active_record/relation/predicate_builder/array_handler.rb', line 10

def call(attribute, value)
  return attribute.in([]) if value.empty?

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

  values_predicate =
    case values.length
    when 0 then NullPredicate
    when 1 then predicate_builder.build(attribute, values.first)
    else
      bind_values = values.map do |v|
        predicate_builder.build_bind_attribute(attribute.name, v)
      end
      attribute.in(bind_values)
    end

  unless nils.empty?
    values_predicate = values_predicate.or(predicate_builder.build(attribute, nil))
  end

  array_predicates = ranges.map { |range| predicate_builder.build(attribute, range) }
  array_predicates.unshift(values_predicate)
  array_predicates.inject(&:or)
end