Class: Sunspot::Search::FieldFacet

Inherits:
QueryFacet show all
Defined in:
sunspot/lib/sunspot/search/field_facet.rb

Overview

A FieldFacet is a facet whose rows are all values for a certain field, in contrast to a QueryFacet, whose rows represent arbitrary queries.

Instance Attribute Summary

Attributes inherited from QueryFacet

name

Instance Method Summary (collapse)

Methods inherited from QueryFacet

#add_row

Constructor Details

- (FieldFacet) initialize(field, search, options)

:nodoc:



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

def initialize(field, search, options) #:nodoc:
  super((options[:name] || field.name).to_sym, search, options)
  @field = field
end

Instance Method Details

- (Object) field_name



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

def field_name
  @field.name
end

- (Object) populate_instances

If this facet references a model class, populate the rows with instances of the model class by loading them out of the appropriate adapter.



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'sunspot/lib/sunspot/search/field_facet.rb', line 57

def populate_instances #:nodoc:
  if reference = @field.reference
    values_hash = rows.inject({}) do |hash, row|
      hash[row.value] = row
      hash
    end
    instances = Adapters::DataAccessor.create(Sunspot::Util.full_const_get(reference)).load_all(
      values_hash.keys
    )
    instances.each do |instance|
      values_hash[Adapters::InstanceAdapter.adapt(instance).id].instance = instance
    end
    true
  end
end

- (Object) rows(options = {})

Get the rows returned for this facet.

Options (options)

:verify

Only return rows for which the referenced object exists in the data store. This option is ignored unless the field associated with this facet is configured with a :references argument.

Returns

Array

Array of FacetRow objects



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'sunspot/lib/sunspot/search/field_facet.rb', line 31

def rows(options = {})
  if options[:verify]
    verified_rows
  else
    @rows ||=
      begin
        rows = super
        has_query_facets = !rows.empty?
        if @search.facet_response['facet_fields']
          if data = @search.facet_response['facet_fields'][key]
            data.each_slice(2) do |value, count|
              row = FacetRow.new(@field.cast(value), count, self)
              rows << row
            end
          end
        end
        sort_rows!(rows) if has_query_facets
        rows
      end
  end
end