Class: Uberloader::Collection

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

Overview

Holds a set of Uberload sibling instances

Instance Method Summary collapse

Constructor Details

#initialize(context) ⇒ Collection

Returns a new instance of Collection.

Parameters:



5
6
7
8
# File 'lib/uberloader/collection.rb', line 5

def initialize(context)
  @context = context
  @uberloads = {}
end

Instance Method Details

#add(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:



26
27
28
29
30
31
# File 'lib/uberloader/collection.rb', line 26

def add(association, scope: nil, &block)
  u = @uberloads[association] ||= Uberload.new(@context, association)
  u.scope scope if scope
  u.block(&block) if block
  u
end

#add_preload_values(val) ⇒ Object

Add preload values from Rails.

Parameters:

  • val (Symbol|Array|Hash)


38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/uberloader/collection.rb', line 38

def add_preload_values(val)
  case val
  when Hash
    val.each { |k,v| add(k).children.add_preload_values(v) }
  when Array
    val.each { |v| add_preload_values v }
  when String
    add val.to_sym
  when Symbol
    add val
  else
    raise ArgumentError, "Unexpected preload value: #{val.inspect}"
  end
end

#to_hHash

Returns a nested Hash of the uberloaded associations

Returns:

  • (Hash)


60
61
62
63
64
# File 'lib/uberloader/collection.rb', line 60

def to_h
  @uberloads.each_value.reduce({}) { |acc, u|
    acc.merge u.to_h
  }
end

#uberload!(records, strict_loading = false) ⇒ Object

Load @uberloads into records



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

def uberload!(records, strict_loading = false)
  @uberloads.each_value { |u| u.uberload!(records, strict_loading) }
end