Class: Dashes::Table

Inherits:
Node
  • Object
show all
Defined in:
lib/dashes.rb

Instance Method Summary collapse

Constructor Details

#initializeTable

Returns a new instance of Table.



33
34
35
36
37
38
39
40
# File 'lib/dashes.rb', line 33

def initialize
  @rows = []
  @separators = []
  @aligns = []
  @width = nil
  @max_width = nil
  @spacing = nil
end

Instance Method Details

#align(*alignments) ⇒ Object



52
53
54
55
# File 'lib/dashes.rb', line 52

def align(*alignments)
  @aligns = alignments
  self
end

#max_width(max_width) ⇒ Object



62
63
64
65
# File 'lib/dashes.rb', line 62

def max_width(max_width)
  @max_width = max_width
  self
end

#row(*data) ⇒ Object



42
43
44
45
# File 'lib/dashes.rb', line 42

def row(*data)
  @rows << data.map(&:to_s)
  self
end

#separatorObject



47
48
49
50
# File 'lib/dashes.rb', line 47

def separator
  @separators << @rows.length
  self
end

#spacing(*spacing) ⇒ Object



67
68
69
70
# File 'lib/dashes.rb', line 67

def spacing(*spacing)
  @spacing = spacing
  self
end

#to_sObject



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/dashes.rb', line 72

def to_s
  return '' if @rows.empty?
  widths = col_widths
  format = []
  separator = "+-#{widths.map {|w| '-'*w}.join('-+-')}-+"
  format << separator
  @rows.each_with_index do |row, index|
    @separators.select { |s| s == index }.count.times { format << separator }
    line = []
    row.each_with_index do |data, col|
      line << cell(data, widths[col], @aligns[col] || :left)
    end
    format << "| #{line.join(' | ')} |"
  end
  @separators.select { |s| s == @rows.length }.count.times { format << separator }
  format << separator
  format.join("\n")
end

#total_widthObject



91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/dashes.rb', line 91

def total_width
  if @rows.empty?
    0
  elsif @width
    @width
  else
    width = col_widths.reduce { |a,b| a+b }
    cols = @rows.first.size
    twidth = width + (2 * cols) + (cols + 1)
    @max_width ? [twidth, @max_width].min : twidth
  end
end

#width(width) ⇒ Object



57
58
59
60
# File 'lib/dashes.rb', line 57

def width(width)
  @width = width
  self
end