Permalink
Find file
Fetching contributors…
Cannot retrieve contributors at this time
57 lines (47 sloc) 1.66 KB
module ActiveRecord
class PredicateBuilder
class ArrayHandler # :nodoc:
def initialize(predicate_builder)
@predicate_builder = predicate_builder
end
def call(attribute, value)
return attribute.in([]) if value.empty?
return queries_predicates(value) if value.all? { |v| v.is_a?(Hash) }
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 attribute.in(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
# TODO Change this to private once we've dropped Ruby 2.2 support.
# Workaround for Ruby 2.2 "private attribute?" warning.
protected
attr_reader :predicate_builder
module NullPredicate # :nodoc:
def self.or(other)
other
end
end
private
def queries_predicates(queries)
if queries.size > 1
queries.map do |query|
Arel::Nodes::And.new(predicate_builder.build_from_hash(query))
end.inject(&:or)
else
predicate_builder.build_from_hash(queries.first)
end
end
end
end
end