Module: Motor::ApiQuery::Search
- Defined in:
- lib/motor/api_query/search.rb
Constant Summary collapse
- STRING_COLUMN_TYPES =
%i[text string].freeze
- NUMBER_COLUMN_TYPES =
%i[integer float].freeze
Class Method Summary collapse
- .build_arel_filters(model, column_names, keyword) ⇒ Object
- .build_arel_or_query(filter_array) ⇒ Object
- .call(rel, keyword) ⇒ Object
- .fetch_filters(rel, keyword) ⇒ Object
- .find_searchable_columns(model) ⇒ Object
Class Method Details
.build_arel_filters(model, column_names, keyword) ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/motor/api_query/search.rb', line 29 def build_arel_filters(model, column_names, keyword) arel_table = model.arel_table column_names.map do |name| column_type = model.columns_hash[name].type if STRING_COLUMN_TYPES.include?(column_type) arel_table[name].matches("%#{keyword}%") elsif NUMBER_COLUMN_TYPES.include?(column_type) arel_table[name].eq(keyword.to_f) else arel_table[name].eq(keyword) end end end |
.build_arel_or_query(filter_array) ⇒ Object
45 46 47 48 49 50 51 |
# File 'lib/motor/api_query/search.rb', line 45 def build_arel_or_query(filter_array) filter_array.reduce(nil) do |acc, filter| next acc = filter unless acc acc.or(filter) end end |
.call(rel, keyword) ⇒ Object
11 12 13 14 15 16 17 18 19 |
# File 'lib/motor/api_query/search.rb', line 11 def call(rel, keyword) return rel if keyword.blank? filters = fetch_filters(rel, keyword) arel_where = build_arel_or_query(filters) rel.where(arel_where) end |
.fetch_filters(rel, keyword) ⇒ Object
21 22 23 24 25 26 27 |
# File 'lib/motor/api_query/search.rb', line 21 def fetch_filters(rel, keyword) klass = rel.klass selected_columns = find_searchable_columns(klass) build_arel_filters(klass, selected_columns, keyword) end |
.find_searchable_columns(model) ⇒ Object
53 54 55 |
# File 'lib/motor/api_query/search.rb', line 53 def find_searchable_columns(model) model.try(:motor_searchable_columns) || Motor::BuildSchema::FindSearchableColumns.call(model) end |