Class: Uberloader::Uberload

Inherits:
Object
  • Object
show all
Defined in:
lib/uberloader/uberload.rb

Overview

Describes an association to preload (and its children)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(context, name, scope: nil) {|Uberloader::Context| ... } ⇒ Uberload

Returns a new instance of Uberload.

Parameters:

  • context (Uberloader::Context)
  • name (Symbol)

    Name of the association

  • scope (ActiveRecord::Relation) (defaults to: nil)

    optional scope to apply to the association’s query

Yields:



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

#childrenUberloader::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)
  }

Parameters:

  • rel (ActiveRecord::Relation)

Returns:



54
55
56
57
# File 'lib/uberloader/uberload.rb', line 54

def scope(rel)
  @scopes << rel
  self
end

#to_hHash

Returns a nested Hash of the uberloaded associations

Returns:

  • (Hash)


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)
    }
  }

Parameters:

  • association (Symbol)

    Name of the association

  • scope (ActiveRecord::Relation) (defaults to: nil)

    Optional scope to apply to the association’s query

Yields:

Returns:



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