Created
May 16, 2017 12:16
-
-
Save Shekharrajak/8cde827a623cea588b3ac6afdc2cfc6d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'pivot_table' | |
require 'daru' | |
class Order | |
attr_reader :city, :quarter, :top_sales | |
def initialize args | |
args.each do |k,v| | |
instance_variable_set("@#{k}", v) unless v.nil? | |
end | |
end | |
end | |
obj_1 = Order.new(city: 'London', quarter: 'Q1', top_sales: 'Ed') | |
obj_2 = Order.new(city: 'London', quarter: 'Q2', top_sales: 'Jim') | |
obj_3 = Order.new(city: 'London', quarter: 'Q3', top_sales: 'Sam') | |
obj_4 = Order.new(city: 'London', quarter: 'Q4', top_sales: 'Ed') | |
obj_5 = Order.new(city: 'New York', quarter: 'Q1', top_sales: 'Tom') | |
obj_6 = Order.new(city: 'New York', quarter: 'Q2', top_sales: 'Sandy') | |
obj_7 = Order.new(city: 'New York', quarter: 'Q3', top_sales: 'Phil') | |
obj_8 = Order.new(city: 'New York', quarter: 'Q4', top_sales: 'Jim') | |
data = [ obj_1, obj_2, obj_3, obj_4, obj_5, obj_6, obj_7, obj_8 ] | |
g = PivotTable::Grid.new do |g| | |
g.source_data = data | |
g.column_name = :quarter | |
g.row_name = :city | |
g.value_name = :sales | |
g.field_name = :top_sales | |
end | |
p g.build.data_grid == [['Ed' ,'Jim','Sam','Ed' ], ['Tom' ,'Sandy' ,'Phil','Jim' ]] | |
row_headers = g.row_headers | |
# p row_headers | |
data = g.rows.map {|gg| gg.data} | |
# p data | |
# p "" | |
headers = g.column_headers | |
# p headers | |
# p g.columns.map {|gg| gg.data} | |
# p "" | |
p Daru::Formatters::Table.format(data, headers: headers, row_headers: row_headers) | |
# output: | |
# => " Q1 Q2 Q3 Q4\n London Ed Jim Sam Ed\n New York Tom Sandy Phil Jim" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment