Allows to have a registry of the classes adapted by a DataAccessor. This registry does the class registration using DataAccessor’s create and while doing so also allows a registered class to notify which attributes should be inherited by its subclasses. This is useful in cases such us ActiveRecord’s include option, where you may need to run a search in all the subclasses of a searchable model and including some associations for all of them when it loads.
# ActiveRecordDataAccessor marks :include and :select as inherited_attributes class ActiveRecordDataAccessor < Sunspot::Adapters::DataAccessor
# options for the find attr_accessor :include, :select def initialize(clazz) super(clazz) @inherited_attributes = [:include, :select] end
end
class Event < ActiveRecord::Base
searchable do #stuff here end
end class Play < Event ; end class Movie < Event ; end
# This will push the :include to ALL of the Event’s subclasses @search = Event.search(include: [:images])
# You can also set the value just one class’s attribute @search.data_accessor_for(Play).include = [ :images, :location]
It will inject declared attributes to be inherited from ancestors only if they are not already present in the data_accessor for each class.
# File lib/sunspot/adapters.rb, line 376 def inject_inherited_attributes_for(data_accessor) return data_accessor if @reg.empty? data_accessor.inherited_attributes.each do |attribute| if data_accessor.send(attribute).nil? # Inject only if the current class didn't define one. inherited_value = nil # Now try to find a value for the attribute in the chain of ancestors data_accessor.clazz.ancestors.each do |ancestor| next if ancestor.name.nil? || ancestor.name.empty? key = ancestor.name.to_sym inherited_value = @reg[key].send(attribute) if @reg[key] break unless inherited_value.nil? end data_accessor.send("#{attribute.to_s}=", inherited_value) unless inherited_value.nil? end end data_accessor end
# File lib/sunspot/adapters.rb, line 365 def retrieve(clazz) key = clazz.name.to_sym if !@reg.include?(key) data_accessor = inject_inherited_attributes_for( Adapters::DataAccessor.create(clazz) ) @reg[key] ||= data_accessor end @reg[key] end
# File lib/sunspot/adapters.rb, line 359 def initialize @reg = {} end