Class: ANSI::Table

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(table, options = {}, &format) ⇒ Table

The Table class can be used to output nicely formatted tables with division lines and alignment.

table - array of array

options - align :left or :right options - space to add to each cell options - fit to screen width options -

The format block must return ANSI codes to apply to each cell.

Other Implementations:

TODO: Support for table headers and footers.



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/ansi/table.rb', line 27

def initialize(table, options={}, &format)
  @table   = table
  @padding = options[:padding] || 0
  @align   = options[:align]
  @fit     = options[:fit]
  @border  = options[:border]
  #@ansi    = [options[:ansi]].flatten
  @format  = format

  @pad = " " * @padding
end

Instance Attribute Details

#alignObject

Returns the value of attribute align.



49
50
51
# File 'lib/ansi/table.rb', line 49

def align
  @align
end

#borderObject

Returns the value of attribute border.



55
56
57
# File 'lib/ansi/table.rb', line 55

def border
  @border
end

#fitObject

Fit to scree width.



43
44
45
# File 'lib/ansi/table.rb', line 43

def fit
  @fit
end

#formatObject

Returns the value of attribute format.



52
53
54
# File 'lib/ansi/table.rb', line 52

def format
  @format
end

#paddingObject

Returns the value of attribute padding.



46
47
48
# File 'lib/ansi/table.rb', line 46

def padding
  @padding
end

#tableObject

Returns the value of attribute table.



40
41
42
# File 'lib/ansi/table.rb', line 40

def table
  @table
end

Instance Method Details

#to_sObject

(fit=false)



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

def to_s #(fit=false)
  row_count = table.size
  col_count = table[0].size

  max = max_columns(fit)

  div = dividing_line
  top = div #.gsub('+', ".")
  bot = div #.gsub('+', "'")

  body = []
  table.each_with_index do |row, r|
     body_row = []
     row.each_with_index do |cell, c|
       t = cell_template(max[c])
       body_row << (t % cell.to_s).ansi(*ansi_formating(cell, c, r))
     end
     body << "| " + body_row.join(' | ') + " |"
  end

  if border
    body = body.join("\n#{div}\n")
  else
    body = body.join("\n")
  end

  "#{top}\n#{body}\n#{bot}\n"
end