Class: Cl::Help::Table

Inherits:
Object
  • Object
show all
Includes:
Wrap
Defined in:
lib/cl/help/table.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Wrap

#wrap

Constructor Details

#initialize(data) ⇒ Table

Returns a new instance of Table.



8
9
10
# File 'lib/cl/help/table.rb', line 8

def initialize(data)
  @data = data
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



6
7
8
# File 'lib/cl/help/table.rb', line 6

def data
  @data
end

#paddingObject (readonly)

Returns the value of attribute padding.



6
7
8
# File 'lib/cl/help/table.rb', line 6

def padding
  @padding
end

Instance Method Details

#any?Boolean

Returns:

  • (Boolean)


12
13
14
# File 'lib/cl/help/table.rb', line 12

def any?
  data.any?
end

#cells(row) ⇒ Object



26
27
28
29
30
# File 'lib/cl/help/table.rb', line 26

def cells(row)
  row.map.with_index do |cell, ix|
    indent(wrap(cell.to_s), widths[ix - 1]).ljust(widths[ix])
  end
end

#colsObject



53
54
55
# File 'lib/cl/help/table.rb', line 53

def cols
  @cols ||= data.transpose
end

#format(padding = 8) ⇒ Object Also known as: to_s



16
17
18
19
# File 'lib/cl/help/table.rb', line 16

def format(padding = 8)
  @padding = padding
  rows.join("\n")
end

#indent(str, width) ⇒ Object



32
33
34
35
# File 'lib/cl/help/table.rb', line 32

def indent(str, width)
  return str if str.empty? || !width
  [str.lines[0], *str.lines[1..-1].map { |str| ' ' * (width + 1) + str }].join.rstrip
end

#pad(width, ix) ⇒ Object



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

def pad(width, ix)
  ix < cols.size - 2 ? width : width + padding.to_i
end

#rowsObject



22
23
24
# File 'lib/cl/help/table.rb', line 22

def rows
  data.map { |row| cells(row).join(' ').rstrip }
end

#widthObject



37
38
39
40
# File 'lib/cl/help/table.rb', line 37

def width
  widths = cols[0..-2].map { |col| col.max_by(&:size).size }.inject(&:+).to_i
  widths + cols.size - 1
end

#widthsObject



42
43
44
45
46
47
# File 'lib/cl/help/table.rb', line 42

def widths
  cols.map.with_index do |col, ix|
    max = col.compact.max_by(&:size)
    pad(max ? max.size : 0, ix)
  end
end