Class: Uberloader::Uberload
- Inherits:
-
Object
- Object
- Uberloader::Uberload
- Defined in:
- lib/uberloader/uberload.rb
Overview
Describes an association to preload (and its children)
Instance Attribute Summary collapse
- #children ⇒ Uberloader::Collection readonly
Instance Method Summary collapse
-
#block(&block) ⇒ Object
Run a block against this level.
-
#initialize(context, name, scope: nil) {|Uberloader::Context| ... } ⇒ Uberload
constructor
A new instance of Uberload.
-
#scope(rel) ⇒ Uberloader::Uberload
Append a scope to the association.
-
#to_h ⇒ Hash
Returns a nested Hash of the uberloaded associations.
-
#uberload(association, scope: nil) {|Uberloader::Context| ... } ⇒ Uberloader::Uberload
Uberload an association.
-
#uberload!(parent_records, strict_loading = false) ⇒ Object
Load @children into records.
Constructor Details
#initialize(context, name, scope: nil) {|Uberloader::Context| ... } ⇒ Uberload
Returns a new instance of Uberload.
13 14 15 16 17 18 19 |
# File 'lib/uberloader/uberload.rb', line 13 def initialize(context, name, scope: nil, &block) @context = context @name = name @scopes = scope ? [scope] : [] @children = Collection.new(context) self.block(&block) if block end |
Instance Attribute Details
#children ⇒ Uberloader::Collection (readonly)
5 6 7 |
# File 'lib/uberloader/uberload.rb', line 5 def children @children end |
Instance Method Details
#block(&block) ⇒ Object
Run a block against this level
60 61 62 63 |
# File 'lib/uberloader/uberload.rb', line 60 def block(&block) @context.using(self, &block) self end |
#scope(rel) ⇒ Uberloader::Uberload
Append a scope to the association.
Category.all.
uberload(:widget) { |u|
u.scope Widget.active
u.scope Widget.order(:name)
}
54 55 56 57 |
# File 'lib/uberloader/uberload.rb', line 54 def scope(rel) @scopes << rel self end |
#to_h ⇒ Hash
Returns a nested Hash of the uberloaded associations
79 80 81 82 83 |
# File 'lib/uberloader/uberload.rb', line 79 def to_h h = {} h[@name] = @children.to_h h end |
#uberload(association, scope: nil) {|Uberloader::Context| ... } ⇒ Uberloader::Uberload
Uberload an association.
Category.all.
uberload(:widget, scope: Widget.order(:name)) { |u|
u.uberload(:parts) {
u.scope Part.active
u.uberload(:foo)
}
}
37 38 39 40 |
# File 'lib/uberloader/uberload.rb', line 37 def uberload(association, scope: nil, &block) @children.add(association, scope: scope, &block) self end |
#uberload!(parent_records, strict_loading = false) ⇒ Object
Load @children into records
66 67 68 69 70 71 72 73 74 75 |
# File 'lib/uberloader/uberload.rb', line 66 def uberload!(parent_records, strict_loading = false) # Load @name into parent records Preloader.call(parent_records, @name, scoped(strict_loading)) # Load child records into @name records = parent_records.each_with_object([]) { |parent, acc| acc.concat Array(parent.public_send @name) } @children.uberload! records, strict_loading if records.any? end |