Class: Mongoid::Association::Eager

Inherits:
Object
  • Object
show all
Defined in:
lib/mongoid/association/eager.rb

Overview

Base class for eager load preload functions.

Instance Method Summary collapse

Constructor Details

#initialize(associations, docs, use_lookup = false, pipeline = []) ⇒ Base

Instantiate the eager load class.

Examples:

Create the new belongs to eager load preloader.

BelongsTo.new(association, parent_docs)

Parameters:

  • associations (Array<Mongoid::Association::Relatable>)

    Associations to eager load

  • docs (Array<Document>)

    Documents to preload the associations

  • use_lookup (Boolean) (defaults to: false)

    Whether to use $lookup aggregation for eager loading. This is used in Criteria#eager_load.

  • pipeline (Array<Hash>) (defaults to: [])

    The aggregation pipeline to use when using $lookup for eager loading.



21
22
23
24
25
26
27
# File 'lib/mongoid/association/eager.rb', line 21

def initialize(associations, docs, use_lookup = false, pipeline = [])
  @associations = associations
  @docs = docs
  @grouped_docs = {}
  @use_lookup = use_lookup
  @pipeline = pipeline
end

Instance Method Details

#runArray

Run the preloader.

Examples:

Preload the associations into the documents.

loader.run

Returns:

  • (Array)

    The list of documents given.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/mongoid/association/eager.rb', line 35

def run
  @loaded = []

  if @use_lookup
    preload_with_lookup
    @loaded = @docs
    return @loaded.flatten
  end

  while shift_association
    preload
    @loaded << @docs.collect { |d| d.send(@association.name) if d.respond_to?(@association.name) }
  end
  @loaded.flatten
end