Class: Sunspot::Adapters::Registry

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/sunspot/adapters.rb

Overview

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.

Example

# 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 # You can also set the value just one class’s attribute @search.data_accessor_for(Play).include = [ :images, :location]

Instance Method Summary collapse

Constructor Details

#initializeRegistry

Returns a new instance of Registry.



359
360
361
# File 'lib/sunspot/adapters.rb', line 359

def initialize
  @reg = {}
end

Instance Method Details

#inject_inherited_attributes_for(data_accessor) ⇒ Object

It will inject declared attributes to be inherited from ancestors only if they are not already present in the data_accessor for each class.



376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
# 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

#retrieve(clazz) ⇒ Object



365
366
367
368
369
370
371
372
# 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