Sha256: 8e1027e274ab90d24c2dc1d1f364703d914ecaaf67a872321052d7d808f04397

Contents?: true

Size: 828 Bytes

Versions: 6

Compression:

Stored size: 828 Bytes

Contents

module Agilibox::Search
  extend ActiveSupport::Concern

  class_methods do
    def default_search_fields
      columns.map do |column|
        "#{table_name}.#{column.name}"
      end
    end # def default_search_fields

    def search(q, *fields)
      words  = q.to_s.parameterize.split("-")
      fields = default_search_fields if fields.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_a = words.map.with_index do |word, index|
        ["w#{index}".to_sym, "%#{word}%"]
      end

      sql_params_h = Hash[sql_params_a]

      where(sql_query, sql_params_h)
    end # def search
  end # class_methods
end # class Agilibox::Search

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
agilibox-1.0.15 app/models/concerns/agilibox/search.rb
agilibox-1.0.14 app/models/concerns/agilibox/search.rb
agilibox-1.0.13 app/models/concerns/agilibox/search.rb
agilibox-1.0.12 app/models/concerns/agilibox/search.rb
agilibox-1.0.11 app/models/concerns/agilibox/search.rb
agilibox-1.0.10 app/models/concerns/agilibox/search.rb