Sha256: 686c704336b778dcee2b28314dc0515637ba1e8b2832e50d07a544b8435d4e0e

Contents?: true

Size: 1.45 KB

Versions: 42

Compression:

Stored size: 1.45 KB

Contents

module Virgo
  module SearchHelper

    # Extracts the portion of the document that matches query text.
    # Consider refactoring into a complex activerecord
    # query leveraging "ts_headling". For present though
    # we will perform this with a regex (on the document,
    # which is constructed at the query level -
    # see app/models/concerns/questions/search.rb)
    def search_snippet(document, query, opts={})
      length = opts[:length] || 300

      start_padding = opts[:start_padding] || 30

      words = query.split(" ")

      text = original_text = document

      matcher = Regexp.new(Regexp.union(words).source, Regexp::IGNORECASE)

      if text.length > length
        first_keyword_occurrence = text =~ matcher

        if first_keyword_occurrence && first_keyword_occurrence > start_padding
          start_offset = first_keyword_occurrence - start_padding
        else
          start_offset = 0
        end

        truncated = text.slice(start_offset, text.length)

        text = truncated.slice(0, length)

        if text.length < length
          # pad beginning with existing text
          padding_length = length - text.length
          padding_text = original_text.slice(0, padding_length)
          text = "...#{padding_text}...#{text}..."
        else
          text = "...#{text}..."
        end
      end

      highlighted = text.gsub(matcher) { |match| "<strong class='match'>#{match}</strong>" }

      highlighted.html_safe
    end
  end
end

Version data entries

42 entries across 42 versions & 1 rubygems

Version Path
virgo-0.3.17 app/helpers/virgo/search_helper.rb
virgo-0.3.16 app/helpers/virgo/search_helper.rb
virgo-0.3.15 app/helpers/virgo/search_helper.rb
virgo-0.3.14 app/helpers/virgo/search_helper.rb
virgo-0.3.13 app/helpers/virgo/search_helper.rb
virgo-0.3.12 app/helpers/virgo/search_helper.rb
virgo-0.3.11 app/helpers/virgo/search_helper.rb
virgo-0.3.10 app/helpers/virgo/search_helper.rb
virgo-0.3.9 app/helpers/virgo/search_helper.rb
virgo-0.3.8 app/helpers/virgo/search_helper.rb
virgo-0.3.7 app/helpers/virgo/search_helper.rb
virgo-0.3.6 app/helpers/virgo/search_helper.rb
virgo-0.3.4 app/helpers/virgo/search_helper.rb
virgo-0.3.3 app/helpers/virgo/search_helper.rb
virgo-0.3.2 app/helpers/virgo/search_helper.rb
virgo-0.3.1 app/helpers/virgo/search_helper.rb
virgo-0.3 app/helpers/virgo/search_helper.rb
virgo-0.2.9 app/helpers/virgo/search_helper.rb
virgo-0.2.8 app/helpers/virgo/search_helper.rb
virgo-0.2.7 app/helpers/virgo/search_helper.rb