2018-08-03 13:22:24 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2015-10-07 08:03:18 -04:00
|
|
|
# Concern for querying columns with specific case sensitivity handling.
|
|
|
|
module CaseSensitivity
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
2018-08-27 08:35:31 -04:00
|
|
|
class_methods do
|
2015-10-07 08:03:18 -04:00
|
|
|
# Queries the given columns regardless of the casing used.
|
|
|
|
#
|
|
|
|
# Unlike other ActiveRecord methods this method only operates on a Hash.
|
2015-10-07 11:37:39 -04:00
|
|
|
def iwhere(params)
|
2018-08-20 10:48:08 -04:00
|
|
|
criteria = self
|
2015-10-07 08:03:18 -04:00
|
|
|
|
2020-12-15 10:09:59 -05:00
|
|
|
params.each do |column, value|
|
|
|
|
column = arel_table[column] unless column.is_a?(Arel::Attribute)
|
|
|
|
|
2018-08-20 10:48:08 -04:00
|
|
|
criteria = case value
|
|
|
|
when Array
|
2020-12-15 10:09:59 -05:00
|
|
|
criteria.where(value_in(column, value))
|
2018-08-20 10:48:08 -04:00
|
|
|
else
|
2020-12-15 10:09:59 -05:00
|
|
|
criteria.where(value_equal(column, value))
|
2018-08-20 10:48:08 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
criteria
|
|
|
|
end
|
2015-10-07 08:03:18 -04:00
|
|
|
|
2018-08-20 10:48:08 -04:00
|
|
|
private
|
|
|
|
|
|
|
|
def value_equal(column, value)
|
|
|
|
lower_value = lower_value(value)
|
|
|
|
|
2020-12-15 10:09:59 -05:00
|
|
|
lower_column(column).eq(lower_value).to_sql
|
2018-08-20 10:48:08 -04:00
|
|
|
end
|
2015-10-07 08:03:18 -04:00
|
|
|
|
2018-08-20 10:48:08 -04:00
|
|
|
def value_in(column, values)
|
|
|
|
lower_values = values.map do |value|
|
|
|
|
lower_value(value)
|
2015-10-07 08:03:18 -04:00
|
|
|
end
|
|
|
|
|
2020-12-15 10:09:59 -05:00
|
|
|
lower_column(column).in(lower_values).to_sql
|
2018-08-20 10:48:08 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def lower_value(value)
|
|
|
|
Arel::Nodes::NamedFunction.new('LOWER', [Arel::Nodes.build_quoted(value)])
|
|
|
|
end
|
|
|
|
|
|
|
|
def lower_column(column)
|
|
|
|
column.lower
|
2015-10-07 08:03:18 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|