Class: Sunspot::Field::DynamicField

Inherits:
Object
  • Object
show all
Extended by:
Buildable
Defined in:
lib/sunspot/field.rb

Overview

A DynamicField is a field definition that allows actual fields to be dynamically specified at search/index time. Indexed objects specify the actual fields to be indexed using a hash, whose keys are the dynamic field names and whose values are the values to be indexed.

When indexed, dynamic fields are stored using the dynamic field’s base name, and the runtime-specified dynamic name, separated by a colon. Since colons are not permitted in static Sunspot field names, namespace collisions are prevented.

The use cases for dynamic fields are fairly limited, but certain applications with highly dynamic data models might find them userful.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, type, data_extractor, options) ⇒ DynamicField

Returns a new instance of DynamicField.



167
168
169
170
# File 'lib/sunspot/field.rb', line 167

def initialize(name, type, data_extractor, options)
  @name, @type, @data_extractor = name, type, data_extractor
  @multiple = !!options.delete(:multiple)
end

Instance Attribute Details

#nameObject

Base name of the dynamic field.



165
166
167
# File 'lib/sunspot/field.rb', line 165

def name
  @name
end

Instance Method Details

#build(dynamic_name) ⇒ Object

Build a DynamicFieldInstance representing an actual field to be indexed or searched in Solr.

Parameters

dynamic_name<Symbol>

dynamic name for the field instance

Returns

DynamicFieldInstance

Dynamic field instance



210
211
212
# File 'lib/sunspot/field.rb', line 210

def build(dynamic_name)
  DynamicFieldInstance.new(@name, dynamic_name, @type, @data_extractor, @multiple)
end

#pairs_for(model) ⇒ Object

Return a hash whose keys are fully-qualified field names and whose values are values to be indexed, representing the data to be indexed by this field definition for this model.

Parameters

model<Object>

the model from which to extract the value

Returns

Hash

Key-value pairs representing field names and values to be indexed.



187
188
189
190
191
192
193
194
195
196
# File 'lib/sunspot/field.rb', line 187

def pairs_for(model)
  pairs = {}
  if values = @data_extractor.value_for(model)
    values.each_pair do |dynamic_name, value|
      field_instance = build(dynamic_name)
      pairs[field_instance.indexed_name.to_sym] = field_instance.to_indexed(value)
    end
  end
  pairs
end