Sha256: 469280a81a028a47bdfb4156b2a3921219ad7e9fd3653c351e8f6c856f95e392

Contents?: true

Size: 846 Bytes

Versions: 6

Compression:

Stored size: 846 Bytes

Contents

module Agilibox::Search
  extend ActiveSupport::Concern

  class_methods do
    def default_search_fields
      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 do |word, index|
        fields.map do |field|
          "(UNACCENT(CAST(#{field} AS TEXT)) ILIKE :w#{index})"
        end.join(" OR ")
      end.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]

      self.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.9 app/models/concerns/agilibox/search.rb
agilibox-1.0.8 app/models/concerns/agilibox/search.rb
agilibox-1.0.7 app/models/concerns/agilibox/search.rb
agilibox-1.0.6 app/models/concerns/agilibox/search.rb
agilibox-1.0.5 app/models/concerns/agilibox/search.rb
agilibox-1.0.4 app/models/concerns/agilibox/search.rb