Sha256: 0e9e01ce1be7a2f99dda96529072ad9d4bcdf959713671523cbace46d0305119
Contents?: true
Size: 1.42 KB
Versions: 48
Compression:
Stored size: 1.42 KB
Contents
# frozen_string_literal: true module Motor module ApiQuery module Search STRING_COLUMN_TYPES = %i[text string].freeze NUMBER_COLUMN_TYPES = %i[integer float].freeze module_function 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 def fetch_filters(rel, keyword) klass = rel.klass selected_columns = find_searchable_columns(klass) build_arel_filters(klass, selected_columns, keyword) end 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 def build_arel_or_query(filter_array) filter_array.reduce(nil) do |acc, filter| next acc = filter unless acc acc.or(filter) end end def find_searchable_columns(model) model.try(:motor_searchable_columns) || Motor::BuildSchema::FindSearchableColumns.call(model) end end end end
Version data entries
48 entries across 48 versions & 1 rubygems