-
-
Save hassanrbh/4b9894751c07f4a15cc641cf3cae3b92 to your computer and use it in GitHub Desktop.
The initial implementation of a Whereable query filter for KameSame.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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