Sha256: ef41853d3936ef0786ee24ec8ce55c7b31f1542b1141370aa3c7c1126e725af6

Contents?: true

Size: 792 Bytes

Versions: 1

Compression:

Stored size: 792 Bytes

Contents

module SimpleTables
  class PivotTable < Hash
    def initialize
      self.default=0
    end

    def add_column(name,&block)
      added_columns[name]=block
      self
    end

    def added_columns
      @added_columns||=Hash.new
    end

    def column_headers(all=false)
      return ['#'] + self.keys.map{|k| k[0]}.uniq + added_columns.keys if all

      self.keys.map{|k| k[0]}.uniq
    end

    def row_headers
      self.map{|k,v| k[1]}.uniq
    end

    def rows
      result=[]
      row_headers.each do |rh|
        row = column_headers.map{|ch| self[[ch,rh]]}
        result << [rh] + row + added_columns.values.map{|v| v.call row }
      end

      result
    end

    def as_arrays
      result=[['#']+column_headers(true)]

      result << rows

      result
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
simple_tables-0.0.2 lib/simple_tables/pivot_table.rb