class GroupBySummary
Constants
- VERSION
Attributes
list_of_items[R]
Public Class Methods
new(arr=[])
click to toggle source
Imagine you run a chain of stores that sell different kinds of fruit. Query for store name and kind of fruit in stock: StoreInventory.group(:name, :fruit).pluck(:name, :fruit, ‘sum(quantity)’) [
['Eastside', 'banana', 44], ['Eastside', 'apple', 22], ['Westside', 'banana', 33], ['Westside', 'orange', 44], ['Northside', 'tomato', 55],
]
Order matters here: entity, attributes, value (optional) Also must be ordered by entity.
# File lib/group_by_summary.rb, line 22 def initialize(arr=[]) @list_of_items = Array.new(arr).extend(ArrayNamedAccess) @list_of_items.each { |a| a.extend(ArrayNamedAccess) } end
Public Instance Methods
column_names()
click to toggle source
- ‘apple’, ‘banana’, ‘orange’, ‘tomato’
# File lib/group_by_summary.rb, line 28 def column_names @column_names ||= @list_of_items.collect(&:second).uniq.sort end
heading(entity_name=nil)
click to toggle source
- ‘Store’, ‘apple’, ‘banana’, ‘orange’, ‘tomato’
# File lib/group_by_summary.rb, line 33 def heading(entity_name=nil) [entity_name] + column_names end
heading_with_tabs(entity_name=nil)
click to toggle source
# File lib/group_by_summary.rb, line 37 def heading_with_tabs(entity_name=nil) heading(entity_name).join("\t") end
rows()
click to toggle source
# File lib/group_by_summary.rb, line 41 def rows rows = [] @list_of_items.group_by(&:first).each do |store| store.extend(ArrayNamedAccess) store_row = [nil] * heading.size # Add the entity name to the start of the row. store_row[0] = store.first # Fill in values for each column (remember entity name is already first position). store.second.each do |tuple| store_row[@column_names.index(tuple.second) + 1] = (tuple.third || 'x') end rows << store_row end rows end
rows_with_tabs()
click to toggle source
Ruby’s join is recursive and we want to keep the top level arrays.
# File lib/group_by_summary.rb, line 58 def rows_with_tabs rows.collect { |i| i.join("\t") } end
to_s(opt=nil)
click to toggle source
# File lib/group_by_summary.rb, line 62 def to_s(opt=nil) if opt == :tab [heading_with_tabs] + rows_with_tabs else [heading] + rows end end