4
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
# File 'lib/like_query/model_extensions.rb', line 4
def like(search_string, schema = nil, debug: false, column_search: nil)
_column_search = if [true, false].include?(column_search)
column_search
elsif [true, false].include?(Rails.configuration.x.like_query.column_search)
Rails.configuration.x.like_query.column_search
else
true
end
search_string = '' if !search_string
search_string = search_string.to_s unless search_string.is_a?(String)
schema = [schema] if schema.is_a?(Symbol)
@debug_like_query = debug
raise 'like can only be called from a model' if self == ApplicationRecord
if schema.first.is_a?(Array) && schema.length >= 2
raise "only one array can be given: Either schema as one array or as multiple args, not as array"
end
queries = []
associations = []
available_column_keys = []
@like_query_schema = schema
search_string.split(' ').each do |s|
f_str = format_string_element(s, _column_search)
q = []
(schema.first.is_a?(Array) ? schema.first : schema).each do |p|
dbg("• Iterate schema => #{p}")
enum_lab = enum_keys(p, s)
if enum_lab.present?
_q = arel_table[p].in(enum_lab).to_sql
dbg(-> { " Query from enum => #{_q}" })
q.push(_q)
elsif p.is_a?(Hash)
p.each do |k, v|
assoc = reflect_on_association(k)
raise "Unknown association: :#{k}" unless assoc.present?
associations.push(k.to_sym) unless associations.include?(k.to_sym)
if v.is_a?(Symbol) || v.is_a?(String)
available_column_keys.push([k.to_s, v.to_s].join('.'))
q.push(query_string(v, f_str, assoc))
elsif v.is_a?(Array)
v.each do |_v|
available_column_keys.push([k.to_s, _v.to_s].join('.'))
q.push(query_string(_v, f_str, assoc))
end
else
raise "unknown element: #{p}"
end
end
else
available_column_keys.push(p.to_s)
q.push(query_string(p, f_str))
end
end
if f_str[:column] && !available_column_keys.include?(f_str[:column])
str = I18n.t(
'like_query.column_not_available_error',
default: 'column «%<column>s» is not present within available columns: «%<available_columns>s»'
)
raise format(str, column: f_str[:column], available_columns: available_column_keys.join(', '))
end
__q = q.compact
queries.push("(#{__q.join(' OR ')})") if __q.present?
end
if associations.present?
r = left_outer_joins(associations).where(queries.join(" AND "))
dbg(-> { "RESULT => #{r.to_sql}" })
r
else
r = where(queries.join(" AND "))
dbg(-> { "RESULT => #{r.to_sql}" })
r
end
end
|