Class: Perry::Processors::PreloadAssociations
- Inherits:
-
Object
- Object
- Perry::Processors::PreloadAssociations
- Defined in:
- lib/perry/processors/preload_associations.rb
Overview
Perry::Processors::PreloadAssociations
This adapter processor will allow associations to be eager loaded after the original records are fetched. Any associations specified in an :includes option will be loaded for all records in the query (each association in a single request).
Configuration Options:
None
Modifiers:
None
Instance Method Summary collapse
- #call(options) ⇒ Object
-
#initialize(adapter, config = {}) ⇒ PreloadAssociations
constructor
A new instance of PreloadAssociations.
Constructor Details
#initialize(adapter, config = {}) ⇒ PreloadAssociations
Returns a new instance of PreloadAssociations.
20 21 22 23 |
# File 'lib/perry/processors/preload_associations.rb', line 20 def initialize(adapter, config={}) @adapter = adapter @config = config end |
Instance Method Details
#call(options) ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/perry/processors/preload_associations.rb', line 25 def call() results = @adapter.call() if results && !results.empty? relation = [:relation] (includes = relation.to_hash[:includes] || {}).keys.each do |association_id| association = relation.klass.defined_associations[association_id.to_sym] raise Perry::AssociationNotFound, "unknown association #{association_id}" unless association eager_records = association.scope(results).includes(includes[association_id]).all(:modifiers => [:relation].modifiers_value) results.each do |result| scope = association.scope(result) case association.type when :has_one, :has_many scope.records = eager_records.select do |record| record.send(association.foreign_key) == result.send(association.primary_key) end if association.collection? result.send("#{association.id}=", scope) else result.send("#{association.id}=", scope.records.first) end when :belongs_to scope.records = eager_records.select do |record| record.send(association.primary_key) == result.send(association.foreign_key) end result.send("#{association.id}=", scope.records.first) end end end end results end |