scinote-web/app/models/concerns/searchable_model.rb

60 lines
1.7 KiB
Ruby
Raw Normal View History

2016-02-12 23:52:43 +08:00
module SearchableModel
extend ActiveSupport::Concern
included do
# Helper function for relations that
# adds OR ILIKE where clause for all specified attributes
# for the given search query
scope :where_attributes_like, ->(attributes, query) do
attrs = []
if attributes.blank? or query.blank?
# Do nothing in this case
elsif attributes.is_a? Symbol
attrs = [attributes.to_s]
elsif attributes.is_a? String
attrs = [attributes]
elsif attributes.is_a? Array
attrs = attributes.collect { |a| a.to_s }
else
raise ArgumentError, ":attributes must be an array, symbol or string"
end
2016-07-21 19:11:15 +08:00
if query.is_a? Array
2016-11-14 19:32:41 +08:00
rich_text_regex = '<*strong>|<*href>|<*div>|' \
2016-11-16 21:50:06 +08:00
'<*link>|<*span>|<%class%>|<%href%>|' \
'<%data%>|<*sub>|<*sup>|<*blockquote>|<*li>|' \
'<%style%>|<*ol>|<*ul>|<*pre>'
2016-11-14 19:32:41 +08:00
2016-11-11 18:41:23 +08:00
if attrs.length > 0
2016-07-21 19:11:15 +08:00
where_str =
2016-11-11 18:41:23 +08:00
(attrs.map.with_index do |a, i|
2016-11-14 19:32:41 +08:00
"REGEXP_REPLACE(#{a}, E'#{rich_text_regex}','', 'g')" \
2016-11-11 18:41:23 +08:00
"ILIKE ANY (array[ :t#{i}]) OR "
end
).join[0..-5]
vals = (attrs.map.with_index do |a, i|
["t#{i}".to_sym, query]
end
).to_h
2016-02-12 23:52:43 +08:00
2016-07-21 19:11:15 +08:00
return where(where_str, vals)
end
else
2016-11-11 18:41:23 +08:00
if attrs.length > 0
2016-07-21 19:11:15 +08:00
where_str =
2016-11-11 18:41:23 +08:00
(attrs.map.with_index do |a, i|
2016-11-14 19:32:41 +08:00
"REGEXP_REPLACE(#{a}, E'#{rich_text_regex}'," \
2016-11-11 18:41:23 +08:00
" '', 'g' ) ILIKE :t#{i} OR "
end
).join[0..-5]
2016-07-21 19:11:15 +08:00
vals = (attrs.map.with_index { |a,i| [ "t#{i}".to_sym, "%#{query}%" ] }).to_h
return where(where_str, vals)
end
2016-02-12 23:52:43 +08:00
end
end
end
2016-11-11 18:41:23 +08:00
end