Class: HashMath::Unpivot

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/hash_math/unpivot.rb,
lib/hash_math/unpivot/pivot.rb,
lib/hash_math/unpivot/pivot_set.rb

Overview

This class has the ability to extrapolate one hash (row) into multiple hashes (rows) while unpivoting specific keys into key-value pairs.

Defined Under Namespace

Classes: Pivot, PivotSet

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pivot_set = PivotSet.new) ⇒ Unpivot

Returns a new instance of Unpivot.



22
23
24
25
26
# File 'lib/hash_math/unpivot.rb', line 22

def initialize(pivot_set = PivotSet.new)
  @pivot_set = PivotSet.make(pivot_set, nullable: false)

  freeze
end

Instance Attribute Details

#pivot_setObject (readonly)

Returns the value of attribute pivot_set.



18
19
20
# File 'lib/hash_math/unpivot.rb', line 18

def pivot_set
  @pivot_set
end

Instance Method Details

#expand(hash) ⇒ Object

The main method for this class that performs the un-pivoting and hash expansion. Pass in a hash and it will return an array of hashes.



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/hash_math/unpivot.rb', line 30

def expand(hash)
  return [hash] unless pivot_set.any?

  all_combinations = pivot_set.expand(hash)

  products = all_combinations.inject(all_combinations.shift) do |memo, array|
    memo.product(array)
  end

  recombine(products)
end