module Gummi module Fields class SanitizedString < Virtus::Attribute def coerce(value) return nil if value.blank? sanitize_string_for_query(value.to_s) end def mapping { type: 'string' } end def sanitize_string_for_query(str) # Escape special characters escaped_characters = Regexp.escape('\/\\+-&|!(){}[]^~*?:') str = str.gsub(/([#{escaped_characters}])/) do |match| '\\'+match end # Escape odd quotes quote_count = str.count '"' str = str.gsub(/(.*)"(.*)/, '\1\"\3') if quote_count % 2 == 1 str end end end end