Class: Terminal::Table

Inherits:
Object
  • Object
show all
Defined in:
lib/terminal/table.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize {|_self| ... } ⇒ Table

Returns a new instance of Table.

Yields:

  • (_self)

Yield Parameters:



38
39
40
41
42
43
44
# File 'lib/terminal/table.rb', line 38

def initialize
  @rows = []
  @headings = []
  @column_widths = []
  yield self if block_given?
  recalculate_column_widths!
end

Instance Attribute Details

#column_widthsObject

Returns the value of attribute column_widths.



36
37
38
# File 'lib/terminal/table.rb', line 36

def column_widths
  @column_widths
end

#headingsObject

Returns the value of attribute headings.



35
36
37
# File 'lib/terminal/table.rb', line 35

def headings
  @headings
end

#rowsObject

Returns the value of attribute rows.



34
35
36
# File 'lib/terminal/table.rb', line 34

def rows
  @rows
end

Instance Method Details

#recalculate_column_widths!Object



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/terminal/table.rb', line 46

def recalculate_column_widths!
  if @rows.count > 0
    (0...@rows.first.size).each do |col|
      @column_widths[col] = @rows.map { |row| row[col].to_s.twidth }.max
    end
  end

  if @headings.count > 0
    (0...@headings.size).each do |col|
      @column_widths[col] = [@column_widths[col], @headings[col].twidth].max
    end
  end
end

#to_sObject



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/terminal/table.rb', line 60

def to_s
  result = ''

  header_and_footer = '+' + @column_widths.map { |w| '-' * (w + 2) }.join('+') + '+' + "\n"

  if @headings.count > 0
    result += header_and_footer

    content = @headings.each_with_index.map { |grid, i| grid.to_s.tljust(@column_widths[i]) }

    result += '| ' + content.join(' | ') + " |\n"
  end

  result += header_and_footer

  @rows.each do |row|
    content = row.each_with_index.map { |grid, i| grid.to_s.tljust(@column_widths[i]) }

    result += '| ' + content.join(' | ') + " |\n"
  end

  result + header_and_footer
end