Class: Cardigan::Command::TotalCards

Inherits:
Object
  • Object
show all
Defined in:
lib/cardigan/command/total_cards.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(repository, io) ⇒ TotalCards

Returns a new instance of TotalCards.



7
8
9
10
11
# File 'lib/cardigan/command/total_cards.rb', line 7

def initialize repository, io
  @repository, @io = repository, io
  @usage = '<numeric field> <grouping field>*'
  @help = 'Calculates totals for the specified numeric field aggregated across the specified grouping fields'
end

Instance Attribute Details

#helpObject (readonly)

Returns the value of attribute help.



5
6
7
# File 'lib/cardigan/command/total_cards.rb', line 5

def help
  @help
end

#usageObject (readonly)

Returns the value of attribute usage.



5
6
7
# File 'lib/cardigan/command/total_cards.rb', line 5

def usage
  @usage
end

Instance Method Details

#execute(text = nil) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/cardigan/command/total_cards.rb', line 13

def execute text=nil    
  count_field, *grouping_fields = text.scan(/\w+/) if text
  unless count_field
    @io.say 'missing required numeric total field'
    return
  end
  counts = {}
  total = 0
  @repository.cards.each do |card|
    key = grouping_fields.map {|grouping_field| card[grouping_field] ? card[grouping_field] : ''}
    value = card[count_field].to_i
    counts[key] = counts[key] ? counts[key] + value : value
    total += value
  end

  values = counts.keys.sort.map do |key|
    hash = {count_field => counts[key]}
    grouping_fields.each_with_index {|grouping_field,index| hash[grouping_field] = key[index] }
    hash
  end

  values << {count_field => total} unless counts.size == 1

  formatter = Cardigan::TextReportFormatter.new @io
  grouping_fields.each {|grouping_field| formatter.add_column(grouping_field, 0)}
  formatter.add_column(count_field, 0)
  formatter.output values, :suppress_index => true
end