Module: DefaultWhere::Like

Included in:
DefaultWhere
Defined in:
lib/default_where/like.rb

Constant Summary collapse

PATTERN =
['-like', '-rl', '-ll']

Instance Method Summary collapse

Instance Method Details

#filter_like(params) ⇒ Object



40
41
42
43
44
# File 'lib/default_where/like.rb', line 40

def filter_like(params)
  params.select do |k, _|
    k.end_with?(*PATTERN)
  end
end

#like_scope(params) ⇒ Object



5
6
7
8
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
# File 'lib/default_where/like.rb', line 5

def like_scope(params)
  where_string = []
  where_hash = {}

  params.each do |key, value|
    real_key = key.sub(/-like$/, '')
    agent_key = key.gsub(/[-.]/, '_')

    if column_names.include?(real_key)
      real_key = "#{table_name}.#{real_key}"
    end

    where_string << "#{real_key} like :#{agent_key}"

    if key.end_with?('-ll')
      like_value = "#{value}%"
    elsif key.end_with?('-rl')
      like_value = "%#{value}"
    else
      like_value = "%#{value}%"
    end

    where_hash.merge! agent_key.to_sym => like_value
  end

  where_string = where_string.join ' AND '

  if where_string.present?
    condition = [where_string, where_hash]
    where(condition)
  else
    all
  end
end