Class: Cardigan::Command::CountCards

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(repository, io) ⇒ CountCards

Returns a new instance of CountCards.



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

def initialize repository, io
  @repository, @io = repository, io
  @usage = "<grouping field>*"
  @help = "Counts cards 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/count_cards.rb', line 5

def help
  @help
end

#usageObject (readonly)

Returns the value of attribute usage.



5
6
7
# File 'lib/cardigan/command/count_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/count_cards.rb', line 13

def execute text=nil
  text = '' unless text
  grouping_fields = text.scan(/\w+/)
  lengths = Array.new(grouping_fields.size, 0)
  counts = {}
  total = 0
  @repository.cards.each do |card|
    grouping_fields.each_with_index do |grouping_field,index|
      lengths[index] = card[grouping_field].size if card[grouping_field] and card[grouping_field].size > lengths[index]
    end
    key = grouping_fields.map {|key| card[key] ? card[key] : ''}
    counts[key] = counts[key] ? counts[key] + 1 : 1
    total += 1
  end

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

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

  formatter = Cardigan::TextReportFormatter.new @io
  grouping_fields.each_with_index {|grouping_field,index| formatter.add_column(grouping_field, lengths[index])}
  formatter.add_column('count', 0)
  formatter.output values, :suppress_index => true
end