Sha256: a71847e46c07758a4ec88d89d15bee69410cf9850d1d70ff8fbd004769fad8e1

Contents?: true

Size: 847 Bytes

Versions: 5

Compression:

Stored size: 847 Bytes

Contents

module BMC::Search
  extend ActiveSupport::Concern

  class_methods do
    def default_search_fields
      columns
        .select { |column| column.type.in?([:string, :text]) }
        .map    { |column| "#{table_name}.#{column.name}" }
    end # def default_search_fields

    def search(q, *fields)
      words  = q.to_s.parameterize.split("-")
      fields = default_search_fields if fields.empty?

      return all if words.empty?

      sql_query = words.map.with_index { |_word, index|
        fields.map { |field|
          "(UNACCENT(CAST(#{field} AS TEXT)) ILIKE :w#{index})"
        }.join(" OR ")
      }.map { |e| "(#{e})" }.join(" AND ")

      sql_params = words.map.with_index { |word, index| [:"w#{index}", "%#{word}%"] }.to_h

      where(sql_query, sql_params)
    end # def search
  end # class_methods
end # class BMC::Search

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
bmc-1.6.2 app/models/concerns/bmc/search.rb
bmc-1.6.1 app/models/concerns/bmc/search.rb
bmc-1.6.0 app/models/concerns/bmc/search.rb
bmc-1.5.1 app/models/concerns/bmc/search.rb
bmc-1.5.0 app/models/concerns/bmc/search.rb