Class: Sunspot::Search::Hit

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

Constant Summary collapse

SPECIAL_KEYS =

:nodoc:

Set.new(%w(id type score))

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(raw_hit, search) ⇒ Hit

:nodoc:



22
23
24
25
26
27
28
# File 'lib/sunspot/search/hit.rb', line 22

def initialize(raw_hit, search) #:nodoc:
  @class_name, @primary_key = *raw_hit['id'].match(/([^ ]+) (.+)/)[1..2]
  @score = raw_hit['score']
  @search = search
  @stored_values = raw_hit
  @stored_cache = {}
end

Instance Attribute Details

#class_nameObject (readonly)

Class name of object associated with this hit, as string.



13
14
15
# File 'lib/sunspot/search/hit.rb', line 13

def class_name
  @class_name
end

#instanceObject

Retrieve the instance associated with this hit. This is lazy-loaded, but the first time it is called on any hit, all the hits for the search will load their instances using the adapter’s #load_all method.



54
55
56
57
58
59
# File 'lib/sunspot/search/hit.rb', line 54

def instance
  if @instance.nil?
    @search.populate_hits!
  end
  @instance
end

#primary_keyObject (readonly)

Primary key of object associated with this hit, as string.



9
10
11
# File 'lib/sunspot/search/hit.rb', line 9

def primary_key
  @primary_key
end

#scoreObject (readonly)

Keyword relevance score associated with this result. Nil if this hit is not from a keyword search.



18
19
20
# File 'lib/sunspot/search/hit.rb', line 18

def score
  @score
end

Instance Method Details

#inspectObject



61
62
63
# File 'lib/sunspot/search/hit.rb', line 61

def inspect
  "#<Sunspot::Search::Hit:#{@class_name} #{@primary_key}>"
end

#stored(field_name) ⇒ Object

Retrieve stored field value. For any attribute field configured with :stored => true, the Hit object will contain the stored value for that field. The value of this field will be typecast according to the type of the field.

Parameters

field_name<Symbol>

The name of the field for which to retrieve the stored value.



41
42
43
44
45
46
47
# File 'lib/sunspot/search/hit.rb', line 41

def stored(field_name)
  @stored_cache[field_name.to_sym] ||=
    begin
      field = Sunspot::Setup.for(@class_name).field(field_name)
      field.cast(@stored_values[field.indexed_name])
    end
end