Class: LikeQuery::Formatter

Inherits:
Object
  • Object
show all
Defined in:
lib/like_query/formatter.rb

Constant Summary collapse

COLUMN_REGEX_CASE_SENSITIVE =
/^[a-z_\.0-9]+(?=:)/
COLUMN_REGEX_CASE_INSENSITIVE =
/^[a-zA-Z_\.0-9]+(?=:)/

Class Method Summary collapse

Class Method Details

.translate_columns(search_string, column_translations, case_sensitive: true) ⇒ Object

Translate columns for more convenient usage

second parameter is always a Array of Arrays Example: translate_columns(‘d:50’, [[:d,:diameter], [‘w’, ‘width’]], case_sensitive: false)

> “diameter:50”



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/like_query/formatter.rb', line 12

def self.translate_columns(search_string, column_translations, case_sensitive: true)
  search_string.split(' ').map do |str|

    reg = (case_sensitive ? COLUMN_REGEX_CASE_SENSITIVE : COLUMN_REGEX_CASE_INSENSITIVE)

    column = if case_sensitive
               str.match(reg)
             else
               str.downcase.match(reg)
             end
    if column
      column_translations.each do |tr|
        key = (case_sensitive ? tr.first : tr.first.downcase).to_s
        if column.to_s == key
          str = str.sub(reg, tr.second.to_s)
          break
        end
      end
    end
    str
  end.join(' ')
end