activerecord-hackery--ransack/lib/ransack/adapters/active_record/ransack/nodes/condition.rb

70 lines
2.1 KiB
Ruby
Raw Normal View History

2014-08-01 06:36:12 +00:00
module Ransack
module Nodes
class Condition
def arel_predicate
attributes.map { |attribute|
association = attribute.parent
if negative? && attribute.associated_collection?
query = context.build_correlated_subquery(association)
context.remove_association(association)
2017-06-01 07:54:53 +00:00
if self.predicate_name == 'not_null' && self.value
query.where(format_predicate(attribute))
Arel::Nodes::In.new(context.primary_key, Arel.sql(query.to_sql))
else
query.where(format_predicate(attribute).not)
Arel::Nodes::NotIn.new(context.primary_key, Arel.sql(query.to_sql))
end
else
format_predicate(attribute)
end
}.reduce(combinator_method)
2015-01-16 10:40:40 +00:00
end
private
def combinator_method
combinator === Constants::OR ? :or : :and
2014-08-01 06:36:12 +00:00
end
def format_predicate(attribute)
arel_pred = arel_predicate_for_attribute(attribute)
arel_values = formatted_values_for_attribute(attribute)
2019-11-05 15:54:02 +00:00
predicate = attr_value_for_attribute(attribute).public_send(arel_pred, arel_values)
2016-07-01 07:06:44 +00:00
if in_predicate?(predicate)
predicate.right = predicate.right.map do |pr|
casted_array?(pr) ? format_values_for(pr) : pr
2016-07-01 07:06:44 +00:00
end
end
2016-07-01 07:06:44 +00:00
predicate
end
2015-01-16 10:40:40 +00:00
2016-07-01 07:06:44 +00:00
def in_predicate?(predicate)
return unless defined?(Arel::Nodes::Casted)
predicate.class == Arel::Nodes::In || predicate.class == Arel::Nodes::NotIn
2016-07-01 07:06:44 +00:00
end
def casted_array?(predicate)
2021-08-24 00:30:08 +00:00
value_from(predicate).is_a?(Array) && predicate.is_a?(Arel::Nodes::Casted)
end
2021-08-24 00:30:08 +00:00
def value_from(predicate)
if predicate.respond_to?(:value)
predicate.value # Rails 6.1
elsif predicate.respond_to?(:val)
2022-03-04 12:58:28 +00:00
predicate.val # Rails 6.0
2021-08-24 00:30:08 +00:00
end
end
2020-11-20 12:28:33 +00:00
2021-08-24 00:30:08 +00:00
def format_values_for(predicate)
value_from(predicate).map do |val|
2020-11-20 12:28:33 +00:00
val.is_a?(String) ? Arel::Nodes.build_quoted(val) : val
2015-01-16 10:40:40 +00:00
end
end
end
2014-08-01 06:36:12 +00:00
end
end