Class: Daddy::Utils::SqlUtils

Inherits:
Object
  • Object
show all
Defined in:
lib/daddy/utils/sql_utils.rb

Class Method Summary collapse

Class Method Details

.escape_search(str) ⇒ Object



5
6
7
# File 'lib/daddy/utils/sql_utils.rb', line 5

def self.escape_search(str)
  str.gsub(/\\/, '\\\\\\\\').gsub(/%/, '\%').gsub(/_/, '\_')
end

.like(columns, keywords) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/daddy/utils/sql_utils.rb', line 9

def self.like(columns, keywords)
  target_columns = columns.is_a?(Array) ? columns : [columns]

  sql = []
  sql[0] = '('
    
  keywords.gsub(/ /, ' ').split.each_with_index do |s, i|
    like = SqlUtils.escape_search(s)

    sql[0]  << ' or ' if i > 0
    sql[0] << '('

    target_columns.each_with_index do |column, j|
      sql[0] << ' or ' if j > 0
      sql[0] << "#{column} like ?"
      sql << '%' + like + '%'
    end
    
    sql[0] << ')'
  end
    
  sql[0]  << ')'
  sql      
end