Class: Sunspot::Search::Highlight

Inherits:
Object
  • Object
show all
Defined in:
sunspot/lib/sunspot/search/highlight.rb

Overview

A Highlight represents a single highlighted fragment of text from a document. Depending on the highlighting parameters used for search, there may be more than one Highlight object for a given field in a given result.

Constant Summary

HIGHLIGHT_MATCHER =

:nodoc:

/@@@hl@@@(.*?)@@@endhl@@@/

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (Highlight) initialize(field_name, highlight)

:nodoc:



16
17
18
19
# File 'sunspot/lib/sunspot/search/highlight.rb', line 16

def initialize(field_name, highlight) #:nodoc:
  @field_name = field_name.to_sym
  @highlight = highlight.to_s.strip
end

Instance Attribute Details

- (Object) field_name (readonly)

The name of the field in which the highlight appeared.



14
15
16
# File 'sunspot/lib/sunspot/search/highlight.rb', line 14

def field_name
  @field_name
end

Instance Method Details

- (Object) format(&block) Also known as: formatted

Returns the highlighted text with formatting according to the template given in &block. When no block is given, <em> and </em> are used to surround the highlight.

Example

  search.highlights(:body).first.format { |word| "<strong>#{word}</strong>" }


29
30
31
32
33
34
# File 'sunspot/lib/sunspot/search/highlight.rb', line 29

def format(&block)
  block ||= proc { |word| "<em>#{word}</em>" }
  @highlight.gsub(HIGHLIGHT_MATCHER) do
    block.call(Regexp.last_match[1])
  end
end