Files
nairobi/app/models/concerns/search_cache.rb
Javi Martín 55d339572c Simplify setting tsvector values
We make the code easier to read and at the same time we remove a SQL
injection false positive regarding the use of `WHERE id = #{id}`.

We still get a warning about SQL injection regarding the `tsv =` part.
It's a false positive, since the value of that parameter does not
depend on user input.
2019-11-13 19:52:15 +01:00

33 lines
749 B
Ruby

module SearchCache
extend ActiveSupport::Concern
included do
after_save :calculate_tsvector
end
def calculate_tsvector
self.class.where(id: id).update_all("tsv = (#{searchable_values_sql})")
end
private
def searchable_values_sql
searchable_values
.select { |k, _| k.present? }
.map { |value, weight| set_tsvector(value, weight) }
.join(" || ")
end
def set_tsvector(value, weight)
"setweight(to_tsvector('spanish', unaccent(coalesce(#{quote(strip_html(value))}, ''))), #{quote(weight)})"
end
def quote(value)
ActiveRecord::Base.connection.quote(value)
end
def strip_html(value)
ActionController::Base.helpers.sanitize(value, tags: [])
end
end