Class: PgSearch::Features::TSearch

Inherits:
Feature
  • Object
show all
Defined in:
lib/pg_search_multiple_highlight/tsearch.rb

Overview

Extends class to enable multiple_ighlight method for the search results

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.valid_optionsObject



8
9
10
# File 'lib/pg_search_multiple_highlight/tsearch.rb', line 8

def self.valid_options
  super + %i[dictionary prefix negation any_word normalization tsvector_column highlight multiple_highlight]
end

Instance Method Details

#highlight_multiple_fields(text, query) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/pg_search_multiple_highlight/tsearch.rb', line 29

def highlight_multiple_fields(text, query)
  split_words = query.split(/\s+/).map { |word| Regexp.escape(word) }

  regex = Regexp.new("\\b(#{split_words.join("|")})\\b", Regexp::IGNORECASE)

  text.gsub(regex) { |match| "<mark>#{match}</mark>" }
end

#multiple_highlightObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/pg_search_multiple_highlight/tsearch.rb', line 12

def multiple_highlight
  config = @normalizer.instance_variable_get(:@config)

  against_columns = config.instance_variable_get(:@options)[:against].keys

  @model.search(query).map do |result|
    highlighted_fields = {
      id: result.id
    }
    against_columns.each do |column|
      highlighted_fields[column] = highlight_multiple_fields(result.send(column), query)
    end

    highlighted_fields
  end
end