From 85ff6fe4a506d34222a7b59b8f4778298e27ee32 Mon Sep 17 00:00:00 2001 From: aharpervc Date: Wed, 24 Oct 2018 16:55:26 -0400 Subject: [PATCH] Fix unhandled exception when starting subtotals with an index > 0 - the `collection` is empty and you set `collection[1] = {}`, then `collection[0]` will be `nil` and that'll cause things to blow up --- lib/data-table/table.rb | 8 ++++++-- spec/table_spec.rb | 13 +++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/lib/data-table/table.rb b/lib/data-table/table.rb index e2c6aa7..d264fab 100644 --- a/lib/data-table/table.rb +++ b/lib/data-table/table.rb @@ -339,7 +339,9 @@ def calculate_subtotals! @collection.each_pair_with_parents(@groupings.count) do |group_name, group_data, parents| path = parents + [group_name] result = calculate(group_data, subtotal[0], subtotal[1], path) - @subtotal_calculations[path][index] ||= {} + (0..index).each do |index| + @subtotal_calculations[path][index] ||= {} + end @subtotal_calculations[path][index][subtotal[0]] = {subtotal[1] => result} end end @@ -436,7 +438,9 @@ def calculate_min(collection, column_name) def total_row(collection, column_name, function = nil, index = nil, &block) function_or_block = function || block f = function && block_given? ? [function, block] : function_or_block - collection[index] = {} if collection[index].nil? + (0..index).each do |index| + collection[index] = {} if collection[index].nil? + end collection[index][column_name] = f end end diff --git a/spec/table_spec.rb b/spec/table_spec.rb index eb60edd..e82e099 100644 --- a/spec/table_spec.rb +++ b/spec/table_spec.rb @@ -72,6 +72,19 @@ expect(data_table.subtotal_calculations).to eq({["Star Wars"]=>[{:power_level=>{:sum=>145.0}}], ["Middle Earth"]=>[{:power_level=>{:sum=>9081.0}}]}) end + it "should do sub-totaling starting with indexes > 0" do + data_table.group_by :world, level: 0 + data_table.column :power_level + data_table.subtotal :power_level, :sum, 1 + + data_table.prepare_data + + expect(data_table.subtotal_calculations).to eq({ + ["Star Wars"] => [{}, {:power_level => {:sum => 145.0}}], + ["Middle Earth"] => [{}, {:power_level => {:sum => 9081.0}}] + }) + end + it "should render a custom header" do data_table.custom_header do th 'Two Columns', :colspan => 2