Class: Mongoid::Relations::Eager::Base
- Inherits:
-
Object
- Object
- Mongoid::Relations::Eager::Base
- Defined in:
- lib/mongoid/relations/eager/base.rb
Overview
Base class for eager load preload functions.
Direct Known Subclasses
Instance Method Summary collapse
-
#each_loaded_document ⇒ Object
Run the preloader.
-
#group_by_key ⇒ Symbol
Return the key to group the current documents.
-
#grouped_docs ⇒ Hash
Return a hash with the current documents grouped by key.
-
#initialize(associations, docs) ⇒ Base
constructor
Instantiate the eager load class.
-
#keys_from_docs ⇒ Array
Group the documents and return the keys.
-
#preload ⇒ Object
Preload the current relation.
-
#run ⇒ Array
Run the preloader.
-
#set_on_parent(id, element) ⇒ Object
Set the pre-loaded document into its parent.
-
#shift_metadata ⇒ Object
Shift the current relation metadata.
Constructor Details
#initialize(associations, docs) ⇒ Base
Instantiate the eager load class.
21 22 23 24 25 |
# File 'lib/mongoid/relations/eager/base.rb', line 21 def initialize(associations, docs) @associations = associations @docs = docs @grouped_docs = {} end |
Instance Method Details
#each_loaded_document ⇒ Object
Run the preloader.
74 75 76 77 78 79 80 |
# File 'lib/mongoid/relations/eager/base.rb', line 74 def each_loaded_document criteria = @metadata.klass.any_in(key => keys_from_docs) criteria.inclusions = criteria.inclusions - [ @metadata ] criteria.each do |doc| yield doc end end |
#group_by_key ⇒ Symbol
Return the key to group the current documents.
This method should be implemented in the subclass
133 134 135 |
# File 'lib/mongoid/relations/eager/base.rb', line 133 def group_by_key raise NotImplementedError end |
#grouped_docs ⇒ Hash
Return a hash with the current documents grouped by key.
105 106 107 108 109 |
# File 'lib/mongoid/relations/eager/base.rb', line 105 def grouped_docs @grouped_docs[@metadata.name] ||= @docs.group_by do |doc| doc.send(group_by_key) end end |
#keys_from_docs ⇒ Array
Group the documents and return the keys
119 120 121 |
# File 'lib/mongoid/relations/eager/base.rb', line 119 def keys_from_docs grouped_docs.keys end |
#preload ⇒ Object
Preload the current relation.
This method should be implemented in the subclass
64 65 66 |
# File 'lib/mongoid/relations/eager/base.rb', line 64 def preload raise NotImplementedError end |
#run ⇒ Array
Run the preloader.
47 48 49 50 51 52 53 54 |
# File 'lib/mongoid/relations/eager/base.rb', line 47 def run @loaded = [] while preload @loaded << @docs.collect { |d| d.send(@metadata.name) } end @loaded.flatten end |
#set_on_parent(id, element) ⇒ Object
Set the pre-loaded document into its parent.
91 92 93 94 95 |
# File 'lib/mongoid/relations/eager/base.rb', line 91 def set_on_parent(id, element) grouped_docs[id].each do |d| set_relation(d, element) end end |
#shift_metadata ⇒ Object
Shift the current relation metadata
35 36 37 |
# File 'lib/mongoid/relations/eager/base.rb', line 35 def @metadata = @associations.shift end |