Module: MagickColumns::ActiveRecord

Defined in:
lib/magick_columns/active_record.rb

Instance Method Summary collapse

Instance Method Details

#has_magick_columns(options = {}) ⇒ Object



3
4
5
6
7
8
9
10
11
12
# File 'lib/magick_columns/active_record.rb', line 3

def has_magick_columns(options = {})
  @@_magick_columns ||= {}
  @@_magick_columns[name] ||= []

  options.each do |field, type|
    column_options = _magick_column_options(type)

    @@_magick_columns[name] << { field: field }.merge(column_options)
  end
end

#magick_search(query) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/magick_columns/active_record.rb', line 14

def magick_search(query)
  or_queries = []
  terms = {}

  MagickColumns::Tokenizer.new(query).extract_terms.each_with_index do |or_term, i|
    and_queries = []

    or_term.each_with_index do |and_term, j|
      mini_query = []

      @@_magick_columns[name].each_with_index do |column, k|
        if column[:condition].call(and_term[:term])
          operator = and_term[:operator] || _map_magick_column_operator(column[:operator])
          terms[:"t_#{i}_#{j}_#{k}"] = column[:mask] % {t: and_term[:term]}

          mini_query << "#{column[:field]} #{operator} :t_#{i}_#{j}_#{k}"
        end
      end

      and_queries << mini_query.join(' OR ')
    end

    or_queries << and_queries.map { |a_q| "(#{a_q})" }.join(' AND ')
  end

  where(or_queries.map { |o_q| "(#{o_q})" }.join(' OR '), terms)
end