Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
The initial implementation of a Whereable query filter for KameSame.
class Whereable
def initialize(where:, model: Item, ranking_conditions: [], valid: true, data_source: nil)
@model = model
@where = where
@data_source = data_source
@ranking_conditions = ranking_conditions
@valid = valid
end
def valid?
@valid
end
def where
return unless @valid
@valid = if !@data_source.present? ||
data_source_results.present?
normalize_where(@where, args: [data_source_results])
end
end
def ranking_conditions
return unless @valid
if @ranking_conditions.respond_to?(:call)
normalize_rankings(@ranking_conditions.call(data_source_results))
else
normalize_rankings(@ranking_conditions)
end
end
private
def data_source_results
@data_source_results ||= @data_source&.call
end
def sanitize(sql, *values)
ActiveRecord::Base.sanitize_sql_for_conditions([sql, *values])
end
def normalize_where(where, args: [])
if where.respond_to?(:to_sql)
where
elsif where.respond_to?(:call)
normalize_where(where.call(*args.compact))
else
@model.where(*sanitize(*@where))
end
end
def normalize_rankings(rankings)
Array.wrap(rankings).map { |ranking|
if ranking.is_a?(Array)
sanitize(*ranking)
else
ranking
end
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment