Skip to content

Instantly share code, notes, and snippets.

@ghaydarov
Forked from searls/whereable.rb
Created September 22, 2022 03:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghaydarov/1533527845780a9588fd6f34c1765f77 to your computer and use it in GitHub Desktop.
Save ghaydarov/1533527845780a9588fd6f34c1765f77 to your computer and use it in GitHub Desktop.
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