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

Version Path
motor-admin-0.2.86 lib/motor/api_query/search.rb
motor-admin-0.2.85 lib/motor/api_query/search.rb
motor-admin-0.2.84 lib/motor/api_query/search.rb
motor-admin-0.2.83 lib/motor/api_query/search.rb
motor-admin-0.2.82 lib/motor/api_query/search.rb
motor-admin-0.2.81 lib/motor/api_query/search.rb
motor-admin-0.2.80 lib/motor/api_query/search.rb
motor-admin-0.2.79 lib/motor/api_query/search.rb
motor-admin-0.2.78 lib/motor/api_query/search.rb
motor-admin-0.2.77 lib/motor/api_query/search.rb
motor-admin-0.2.76 lib/motor/api_query/search.rb
motor-admin-0.2.75 lib/motor/api_query/search.rb
motor-admin-0.2.74 lib/motor/api_query/search.rb
motor-admin-0.2.73 lib/motor/api_query/search.rb
motor-admin-0.2.72 lib/motor/api_query/search.rb
motor-admin-0.2.71 lib/motor/api_query/search.rb
motor-admin-0.2.70 lib/motor/api_query/search.rb
motor-admin-0.2.69 lib/motor/api_query/search.rb
motor-admin-0.2.68 lib/motor/api_query/search.rb
motor-admin-0.2.67 lib/motor/api_query/search.rb