lib/pivot_table/grid.rb in pivot_table-0.5.0 vs lib/pivot_table/grid.rb in pivot_table-1.0.0

- old
+ new

@@ -20,38 +20,38 @@ self end def build_rows @rows = [] - @data_grid.each_with_index do |data, index| - @rows << Row.new( + data_grid.each_with_index do |data, index| + rows << Row.new( :header => row_headers[index], :data => data, :value_name => value_name, :orthogonal_headers => column_headers ) end end def build_columns @columns = [] - @data_grid.transpose.each_with_index do |data, index| - @columns << Column.new( + data_grid.transpose.each_with_index do |data, index| + columns << Column.new( :header => column_headers[index], :data => data, :value_name => value_name, :orthogonal_headers => row_headers ) end end def column_headers - @column_headers ||= headers @column_name + @column_headers ||= headers column_name end def row_headers - @row_headers ||= headers @row_name + @row_headers ||= headers row_name end def column_totals columns.map { |c| c.total } end @@ -65,32 +65,53 @@ end def prepare_grid @data_grid = [] row_headers.count.times do - @data_grid << column_headers.count.times.inject([]) { |col| col << nil } + data_grid << column_headers.count.times.inject([]) { |col| col << nil } end - @data_grid + data_grid end def populate_grid prepare_grid row_headers.each_with_index do |row, row_index| - current_row = [] - column_headers.each_with_index do |col, col_index| - object = @source_data.find { |item| item.send(row_name) == row && item.send(column_name) == col } - has_field_name = field_name && object.respond_to?(field_name) - current_row[col_index] = has_field_name ? object.send(field_name) : object - end - @data_grid[row_index] = current_row + data_grid[row_index] = build_data_row(row) end - @data_grid + data_grid end private def headers(method) - hdrs = @source_data.collect { |c| c.send method }.uniq + hdrs = source_data.collect { |c| c.send method }.uniq configuration.sort ? hdrs.sort : hdrs + end + + def build_data_row(row) + current_row = [] + column_headers.each_with_index do |col, col_index| + current_row[col_index] = derive_row_value(row, col) + end + current_row + end + + def find_data_item(row, col) + source_data.find do |item| + item.send(row_name) == row && item.send(column_name) == col + end + end + + def derive_row_value(row, col) + data_item = find_data_item(row, col) + if has_field_name?(data_item) + data_item.send(field_name) + else + data_item + end + end + + def has_field_name?(data_item) + !!(field_name && data_item.respond_to?(field_name)) end end end