Sha256: 12227059e089b4458b847fed4e2b9a284a0c07a193d03a5f89fbdf853244279a

Contents?: true

Size: 1.09 KB

Versions: 3

Compression:

Stored size: 1.09 KB

Contents

require 'action_view'
require 'active_support/core_ext'
require 'active_support/core_ext/hash/slice'

module ActiveSearch
  class Result < Hash

    DEFAULT_HIGHLIGHT_RADIUS = 50

    include ActionView::Helpers::TextHelper

    def initialize(result, text, options = {})
      locale = (options[:locale] || I18n.locale).to_s

      @text = text
      result.to_hash.each do |k,v|
        unless v.nil?
          self[k.to_s] = v.respond_to?(:has_key?) && v.has_key?(locale) ? v[locale] : v
        end
      end

      self.build_highlighted_fields(options[:radius])
    end

    def slice(*keys)
      ::Hash.new.update(self).slice(*keys)
    end

    protected

    def build_highlighted_fields(radius = nil)
      radius = radius || DEFAULT_HIGHLIGHT_RADIUS

      self["highlighted"] = self.each_with_object({}) do |(k,v), h|
        if v.is_a?(String)
          h[k] = excerpt(v, text_words.first, radius: radius)
          h[k] = highlight(h[k], text_words, highlighter: '<em>\1</em>') unless h[k].nil?
        end
      end
    end

    def text_words
      @text_words ||= @text.scan(/\w+|\n/)
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
activesearch-0.3.2 lib/activesearch/result.rb
activesearch-0.3.1 lib/activesearch/result.rb
activesearch-0.3.0 lib/activesearch/result.rb