Class: CommandLineReporter::Table

Inherits:
Object
  • Object
show all
Includes:
OptionsValidator
Defined in:
lib/command_line_reporter/table.rb

Constant Summary collapse

VALID_OPTIONS =
[:border, :width, :encoding]

Instance Method Summary collapse

Methods included from OptionsValidator

#validate_options

Constructor Details

#initialize(options = {}) ⇒ Table

Returns a new instance of Table.

Raises:

  • (ArgumentError)

8
9
10
11
12
13
14
15
16
17
18
# File 'lib/command_line_reporter/table.rb', line 8

def initialize(options = {})
  self.validate_options(options, *VALID_OPTIONS)

  self.border = options[:border] || false
  self.width = options[:width] || false
  self.encoding = options[:encoding] || CommandLineReporter::DEFAULTS[:encoding]

  @rows = []

  raise ArgumentError, "Invalid encoding" unless [ :ascii, :unicode ].include? self.encoding
end

Instance Method Details

#add(row) ⇒ Object


20
21
22
23
24
25
26
27
28
# File 'lib/command_line_reporter/table.rb', line 20

def add(row)
  # Inheritance from the table
  row.border = self.border

  # Inherit properties from the appropriate row
  inherit_column_attrs(row) if self.rows[0]

  self.rows << row
end

#auto_adjust_widthsObject


42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/command_line_reporter/table.rb', line 42

def auto_adjust_widths
  column_widths = []

  self.rows.each do |row|
    row.columns.each_with_index do |col, i|
      column_widths[i] = [ col.required_width, ( column_widths[i] || 0 ) ].max
    end
  end

  self.rows.each do |row|
    row.columns.each_with_index do |col, i|
      col.width = column_widths[i]
    end
  end
end

#outputObject


30
31
32
33
34
35
36
37
38
39
40
# File 'lib/command_line_reporter/table.rb', line 30

def output
  return if self.rows.size == 0 # we got here with nothing to print to the screen
  auto_adjust_widths if self.width == :auto

  puts separator('first') if self.border
  self.rows.each_with_index do |row, index|
    row.output
    puts separator('middle') if self.border && (index != self.rows.size - 1)
  end
  puts separator('last') if self.border
end