Class: ArcFurnace::MergingHash

Inherits:
Hash
  • Object
show all
Defined in:
lib/arc-furnace/merging_hash.rb

Overview

This allows one to merge multiple rows into one such as:

key, value
  1, foo
  1, bar
  2, baz

Results in:

1 => { key => 1, value: [foo, bar] }
2 => { key => 2, value: baz }

Instance Attribute Summary

Attributes inherited from Hash

#key_column

Attributes inherited from Node

#error_handler, #node_id, #params

Instance Method Summary collapse

Methods inherited from Hash

#each, #finalize, #get, #initialize

Constructor Details

This class inherits a constructor from ArcFurnace::Hash

Instance Method Details

#prepareObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/arc-furnace/merging_hash.rb', line 13

def prepare
  loop do
    break if source.empty?
    row = source.row
    row_key = row[key_column]
    if row_key
      row_entry = hash[row_key] ||= {}
      row.each do |column, values|
        existing_column_values = row_entry[column]
        if existing_column_values && column != key_column
          if existing_column_values.is_a?(Array)
            existing_column_values.concat(Array.wrap(values))
          else
            new_row_entry = Array.wrap(existing_column_values)
            new_row_entry.concat(Array.wrap(values))
            row_entry[column] = new_row_entry
          end
        else
          unless values.nil?
            row_entry[column] = values.dup
          end
        end
      end
    end
  end
end