Class: Burner::Library::Collection::NestedAggregate

Inherits:
JobWithRegister show all
Defined in:
lib/burner/library/collection/nested_aggregate.rb

Overview

Iterate over a collection of objects, calling key on each object, then aggregating the returns of key together into one array. This new derived array will be set as the value for the payload’s register. Leverage the key_mappings option to optionally copy down keys and values from outer to inner records. This job is particularly useful if you have nested arrays but wish to deal with each level/depth in the aggregate.

Expected Payload input: array of objects. Payload output: array of objects.

Constant Summary

Constants inherited from JobWithRegister

JobWithRegister::BLANK

Instance Attribute Summary collapse

Attributes inherited from JobWithRegister

#register

Attributes inherited from Job

#name

Instance Method Summary collapse

Methods included from Util::Arrayable

#array

Constructor Details

#initialize(key:, key_mappings: [], name: '', register: DEFAULT_REGISTER, separator: '') ⇒ NestedAggregate

Returns a new instance of NestedAggregate.

Raises:

  • (ArgumentError)


24
25
26
27
28
29
30
31
32
33
34
# File 'lib/burner/library/collection/nested_aggregate.rb', line 24

def initialize(key:, key_mappings: [], name: '', register: DEFAULT_REGISTER, separator: '')
  super(name: name, register: register)

  raise ArgumentError, 'key is required' if key.to_s.empty?

  @key          = key.to_s
  @key_mappings = Modeling::KeyMapping.array(key_mappings)
  @resolver     = Objectable.resolver(separator: separator.to_s)

  freeze
end

Instance Attribute Details

#keyObject (readonly)

Returns the value of attribute key.



22
23
24
# File 'lib/burner/library/collection/nested_aggregate.rb', line 22

def key
  @key
end

#key_mappingsObject (readonly)

Returns the value of attribute key_mappings.



22
23
24
# File 'lib/burner/library/collection/nested_aggregate.rb', line 22

def key_mappings
  @key_mappings
end

#resolverObject (readonly)

Returns the value of attribute resolver.



22
23
24
# File 'lib/burner/library/collection/nested_aggregate.rb', line 22

def resolver
  @resolver
end

Instance Method Details

#perform(output, payload) ⇒ Object



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

def perform(output, payload)
  records = array(payload[register])
  count   = records.length

  output.detail("Aggregating on key: #{key} for #{count} records(s)")

  # Outer loop on parent records
  payload[register] = records.each_with_object([]) do |record, memo|
    inner_records = resolver.get(record, key)

    # Inner loop on child records
    array(inner_records).each do |inner_record|
      memo << copy_key_mappings(record, inner_record)
    end
  end
end