Module: Mongoid::Association::EagerLoadable

Included in:
Contextual::Memory, Contextual::Mongo
Defined in:
build/mongoid-master/lib/mongoid/association/eager_loadable.rb

Overview

This module defines the eager loading behavior for criteria.

Instance Method Summary collapse

Instance Method Details

#eager_load(docs) ⇒ Object



15
16
17
18
19
20
21
# File 'build/mongoid-master/lib/mongoid/association/eager_loadable.rb', line 15

def eager_load(docs)
  docs.tap do |d|
    if eager_loadable?
      preload(criteria.inclusions, d)
    end
  end
end

#eager_loadable?Boolean

Returns:



11
12
13
# File 'build/mongoid-master/lib/mongoid/association/eager_loadable.rb', line 11

def eager_loadable?
  !criteria.inclusions.empty?
end

#preload(associations, docs) ⇒ Object

Load the associations for the given documents. This will be done recursively to load the associations of the given documents' subdocuments.

Parameters:

  • associations (Array<Association>)

    The associations to load.

  • document (Array<Document>)

    The documents.



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
# File 'build/mongoid-master/lib/mongoid/association/eager_loadable.rb', line 29

def preload(associations, docs)
  assoc_map = associations.group_by(&:inverse_class_name)
  docs_map = {}
  queue = [ klass.to_s ]

  while klass = queue.shift
    if as = assoc_map.delete(klass)
      as.each do |assoc|
        queue << assoc.class_name

        # If this class is nested in the inclusion tree, only load documents
        # for the association above it. If there is no parent association,
        # we will include documents from the documents passed to this method.
        ds = docs
        if assoc.parent_inclusions.length > 0
          ds = assoc.parent_inclusions.map{ |p| docs_map[p].to_a }.flatten
        end

        res = assoc.relation.eager_loader([assoc], ds).run

        docs_map[assoc.name] ||= [].to_set
        docs_map[assoc.name].merge(res)
      end
    end
  end
end