sunspot/sunspot — Issue #111: Sunspot should have better highlighting
Author: nz
Created: 2011-10-19 00:33:15+00:00
State: open

## Dirty output

Firstly, the `Highlight#format` method doesn't play nicely with Rails 3 HTML dirty/safe escaping.

```ruby
search_hit.highlight(field).format{ |term| content_tag(tag, term) }
```

The above will generate a dirty string that will be escaped again in the view. The user would have to call `html_safe` against this output string to bypass that, which is, surprise, unsafe.

## Place nicely with ActionView

The above might be fine for non-Rails pure-Ruby apps. So let's leave `#format` in place. But what we should do for the sake of Rails is play nicely with `ActionView::Helpers::TextHelper#highlight`. To do so, it would be best to simply return an array of phrases to pass to the `highlight` method.

Here's a hack in a demo app of mine which uses the ActionView highlight method, and is html-safe.

```ruby
def highlighted(search_hit, field, tag=:strong)
phrases = search_hit.highlights(:name).map do |highlight|
highlight.instance_eval { @highlight }.scan(/@@@hl@@@([^@]+)@@@endhl@@@/)
end.flatten

highlight search_hit.stored(field).first, phrases
end
```

Rather than do all that work to `instance_eval` and `scan` the highlights, we should create a new method on `Sunspot::Search::Hit` to return all the highlight phrases, for use with `ActionView::Helpers::TextHelper#highlight`.