Class: Reportability::Pivot

Inherits:
Object
  • Object
show all
Defined in:
lib/reportability/pivot.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#pivotObject

Returns the value of attribute pivot.



24
25
26
# File 'lib/reportability/pivot.rb', line 24

def pivot
  @pivot
end

#source_dataObject

Returns the value of attribute source_data.



24
25
26
# File 'lib/reportability/pivot.rb', line 24

def source_data
  @source_data
end

#valuesObject

Returns the value of attribute values.



24
25
26
# File 'lib/reportability/pivot.rb', line 24

def values
  @values
end

Instance Method Details

#call(cols, input) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/reportability/pivot.rb', line 37

def call(cols, input)
  if @project
    projection = input.map { |e| @project.call(e) }
  else
    projection = input
  end
  pivot_idx = 0 # cols.index(pivot)
  group_idx = 1 # cols.index(group)
  value_idx = 2 # cols.index(values)

  out_cols = ['group_by'] + projection.map { |e| e[pivot_idx]  }.uniq.sort
  num_cols = out_cols.length
  rows = { nil => out_cols }

  projection.each do |i|
    raise Reportability::InputDataError, "Invalid row #{i.inspect}" unless i.is_a?(Array) && i.length == 3
    v_group = i[group_idx]
    v_pivot = i[pivot_idx]
    v_value = i[value_idx]

    row = (rows[v_group] ||= new_row(v_group, num_cols))
    value_col = out_cols.index(v_pivot)
    row[value_col] = v_value if value_col
  end
  t = Table.new :cols => out_cols, :rows => rows.values
end

#new_row(v_group, num_cols) ⇒ Object



33
34
35
# File 'lib/reportability/pivot.rb', line 33

def new_row(v_group, num_cols)
  Array.new(num_cols) {|e| v_group if e == 0}
end

#project(&block) ⇒ Object



25
26
27
# File 'lib/reportability/pivot.rb', line 25

def project(&block)
  @project = block
end

#project=(proc) ⇒ Object



29
30
31
# File 'lib/reportability/pivot.rb', line 29

def project=(proc)
  @project = proc
end