Guest User

Untitled

a guest
Feb 20th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. module SolrQuery
  2. class << self
  3. def solr_query(conditions = {})
  4. conditions = conditions.dup # let's not accidentally kill our original params
  5. query_parts = []
  6. keyword = conditions.delete(:keyword) # keyword is magical
  7. if keyword.present?
  8. query_parts << "#{solr_value(keyword, true)}"
  9. end
  10.  
  11. conditions.each do |field, value|
  12. unless value.nil?
  13. query_parts << "#{field}:(#{solr_value(value)})"
  14. end
  15. end
  16.  
  17. if query_parts.empty?
  18. return ""
  19. else
  20. return query_parts.join(" AND ")
  21. end
  22. end
  23. alias :build :solr_query
  24.  
  25. def solr_value(object, downcase=false)
  26. if object.is_a?(Array) # case when Array will break for has_manys
  27. if object.empty?
  28. string = "NIL" # an empty array should be equivalent to "don't match anything"
  29. else
  30. string = object.map do |element|
  31. solr_value(element, downcase)
  32. end.join(" OR ")
  33. downcase = false # don't downcase the ORs
  34. end
  35. elsif object.is_a?(Hash) || object.is_a?(Range)
  36. return solr_range(object) # avoid escaping the *
  37. elsif object.is_a?(ActiveRecord::Base)
  38. string = object.id.to_s
  39. elsif object.is_a?(String)
  40. if downcase && (bits = object.split(" OR ")) && bits.length > 1
  41. return "(#{solr_value(bits, downcase)})"
  42. else
  43. string = object
  44. end
  45. else
  46. string = object.to_s
  47. end
  48. string.downcase! if downcase
  49. return escape_solr_string(string)
  50. end
  51. protected :solr_value
  52.  
  53. def solr_range(object)
  54. min = max = nil
  55. if object.is_a?(Hash)
  56. min = object[:min]
  57. max = object[:max]
  58. else
  59. min = object.first
  60. max = object.last
  61. end
  62. min = solr_value(min) if min
  63. max = solr_value(max) if max
  64.  
  65. min ||= "*"
  66. max ||= "*"
  67.  
  68. return "[#{min} TO #{max}]"
  69. end
  70. protected :solr_range
  71.  
  72. def escape_solr_string(string)
  73. string.gsub(SOLR_ESCAPE_REGEXP, "\\\\\\0").strip
  74. end
  75. protected :escape_solr_string
  76. end
  77.  
  78. SOLR_ESCAPE_CHARACTERS = %w" \ + - ! ( ) : ^ ] { } ~ * ? "
  79. SOLR_ESCAPE_REGEXP = Regexp.new(SOLR_ESCAPE_CHARACTERS.map{|char| Regexp.escape(char)}.join("|"))
  80. end
Add Comment
Please, Sign In to add comment