Class: Bizside::SqlUtils

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

Class Method Summary collapse

Class Method Details

.escape_search(str) ⇒ Object

LIKE検索用に検索文字列をエスケープします。



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

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

.like(columns, query_string, options = {}) ⇒ 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
33
34
35
36
37
38
39
40
41
42
# File 'lib/bizside/sql_utils.rb', line 9

def self.like(columns, query_string, options = {})
  target_columns = columns
  unless target_columns.is_a?(Array)
    target_columns = [target_columns]
  end

  sql = []
  sql[0] = '('

  query_string.gsub(/ /, ' ').split.each_with_index do |s, i|
    like = self.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 ?"

      if options.fetch(:backward_match, false)
        sql << like + '%'
      elsif options.fetch(:forward_match, false)
        sql << '%' + like
      else
        sql << '%' + like + '%'
      end
    end

    sql[0] << ')'
  end

  sql[0]  << ')'
  sql
end