Commit 71f3eae0af484015d8ebf3956261b2d25e22c99b

Authored by Andrew
1 parent 7e14e594
Exists in highlighted

Added highlighted method [skip ci]

README.md
... ... @@ -803,6 +803,14 @@ bands.with_highlights.each do |band, highlights|
803 803 end
804 804 ```
805 805  
  806 +Or
  807 +
  808 +```ruby
  809 +bands.highlighted.each do |band|
  810 + band.name
  811 +end
  812 +```
  813 +
806 814 To change the tag, use:
807 815  
808 816 ```ruby
... ...
lib/searchkick/results.rb
... ... @@ -189,6 +189,26 @@ module Searchkick
189 189 @options[:misspellings]
190 190 end
191 191  
  192 + def highlighted(multiple: false)
  193 + with_highlights(multiple: multiple).map do |result, highlights|
  194 + if result.is_a?(HashWrapper)
  195 + result = result.dup
  196 + highlights.each do |k, v|
  197 + result.send("#{k}=", v)
  198 + end
  199 + else
  200 + result = result.clone
  201 + result.readonly! if result.respond_to?(:readonly!)
  202 + highlights.each do |k, v|
  203 + result.define_singleton_method(k) do
  204 + v
  205 + end
  206 + end
  207 + end
  208 + result
  209 + end
  210 + end
  211 +
192 212 private
193 213  
194 214 def results_query(records, hits)
... ...
test/highlight_test.rb
... ... @@ -86,4 +86,28 @@ class HighlightTest < Minitest::Test
86 86 assert highlight.include?("<em>Cinema</em>")
87 87 end
88 88 end
  89 +
  90 + def test_highlighted
  91 + store_names ["Two Door Cinema Club"]
  92 + result = Product.search("cinema", highlight: true)
  93 +
  94 + product = result.highlighted.first
  95 + assert_equal "Two Door <em>Cinema</em> Club", product.name
  96 + assert product.readonly?
  97 +
  98 + # make sure it doesn't modify original
  99 + assert_equal "Two Door Cinema Club", result.first.name
  100 + assert !result.first.readonly?
  101 + end
  102 +
  103 + def test_highlighted_load_false
  104 + store_names ["Two Door Cinema Club"]
  105 + result = Product.search("cinema", highlight: true, load: false)
  106 + product = result.highlighted.first
  107 + assert_equal "Two Door <em>Cinema</em> Club", product.name
  108 + assert_equal "Two Door <em>Cinema</em> Club", product[:name]
  109 +
  110 + # make sure it doesn't modify original
  111 + assert_equal "Two Door Cinema Club", result.first.name
  112 + end
89 113 end
... ...