Sha256: c56007e3587c4b4147235e175a6a658a316c7b1a3ce80cff76f567b6a6115447

Contents?: true

Size: 2 KB

Versions: 1

Compression:

Stored size: 2 KB

Contents

module PivotTable
  class Grid

    attr_accessor :source_data, :row_name, :column_name, :value_name
    attr_reader :columns, :rows, :data_grid, :configuration

    DEFAULT_OPTIONS = {
      :sort => true
    }

    def initialize(opts = {}, &block)
      yield(self) if block_given?
      @configuration = Configuration.new(DEFAULT_OPTIONS.merge(opts))
    end

    def build
      populate_grid
      build_rows
      build_columns
      self
    end

    def build_rows
      @rows = []
      @data_grid.each_with_index do |data, index|
        @rows << Row.new(
          :header     => row_headers[index],
          :data       => data,
          :value_name => value_name
        )
      end
    end

    def build_columns
      @columns = []
      @data_grid.transpose.each_with_index do |data, index|
        @columns << Column.new(
          :header     => column_headers[index],
          :data       => data,
          :value_name => value_name
        )
      end
    end

    def column_headers
      headers @column_name
    end

    def row_headers
      headers @row_name
    end

    def column_totals
      columns.map { |c| c.total }
    end

    def row_totals
      rows.map { |r| r.total }
    end

    def grand_total
      column_totals.inject(0) { |t, x| t + x }
    end

    def prepare_grid
      @data_grid = []
      row_headers.count.times do
        @data_grid << column_headers.count.times.inject([]) { |col| col << nil }
      end
      @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|
          current_row[col_index] = @source_data.find { |item| item.send(row_name) == row && item.send(column_name) == col }
        end
        @data_grid[row_index] = current_row
      end
      @data_grid
    end

    private

    def headers(method)
      hdrs = @source_data.collect { |c| c.send method }.uniq
      configuration.sort ? hdrs.sort : hdrs
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
pivot_table-0.2.0 lib/pivot_table/grid.rb