Class: Columnist::Table

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

Constant Summary collapse

VALID_OPTIONS =
[:border, :border_color, :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
# File 'lib/columnist/table.rb', line 8

def initialize(options = {})
    self.validate_options(options, *VALID_OPTIONS)
    self.border       = options[:border] || false
    self.border_color = options[:border_color] || false
    self.width        = options[:width] || false
    self.encoding     = options[:encoding] || Columnist::DEFAULTS[:encoding]
    @rows             = []
    raise ArgumentError, 'Invalid encoding' unless [:ascii, :unicode].include? self.encoding
end

Instance Method Details

#add(row) ⇒ Object



18
19
20
21
22
23
24
25
26
27
# File 'lib/columnist/table.rb', line 18

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

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

    self.rows << row
end

#auto_adjust_widthsObject



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

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



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

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