Class: Mongoid::Association::Eager

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

Overview

Base class for eager load preload functions.

Class Method Summary collapse

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.



30
31
32
33
34
35
36
# File 'lib/mongoid/association/eager.rb', line 30

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

Class Method Details

.run(associations, docs, use_lookup = false, pipeline = []) ⇒ Array

Build a preloader for the given arguments and run it.

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.

Returns:

  • (Array)

    The list of documents given.



12
13
14
# File 'lib/mongoid/association/eager.rb', line 12

def self.run(associations, docs, use_lookup = false, pipeline = [])
  new(associations, docs, use_lookup, pipeline).run
end

Instance Method Details

#runArray

Run the preloader.

Examples:

Preload the associations into the documents.

loader.run

Returns:

  • (Array)

    The list of documents given.



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/mongoid/association/eager.rb', line 44

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