Class: VisualWidth::Table
- Inherits:
-
Object
- Object
- VisualWidth::Table
- Includes:
- VisualWidth
- Defined in:
- lib/visual_width/table.rb
Constant Summary
Constants included from VisualWidth
Ambiguous, EAST_ASIAN, Fullwide, VERSION, Wide
Instance Attribute Summary collapse
-
#header ⇒ Object
Returns the value of attribute header.
-
#style ⇒ Object
Returns the value of attribute style.
Instance Method Summary collapse
- #draw(*args) ⇒ Object
-
#initialize(header: nil, style: []) ⇒ Table
constructor
A new instance of Table.
- #render(rows, header: nil, output: "") ⇒ Object
Methods included from VisualWidth
count, each_width, measure, truncate
Constructor Details
#initialize(header: nil, style: []) ⇒ Table
Returns a new instance of Table.
9 10 11 12 13 14 |
# File 'lib/visual_width/table.rb', line 9 def initialize(header: nil, style: []) @header = header @style = style @needs_wrap = @style.any? { |style| style[:width] != nil } end |
Instance Attribute Details
#header ⇒ Object
Returns the value of attribute header.
7 8 9 |
# File 'lib/visual_width/table.rb', line 7 def header @header end |
#style ⇒ Object
Returns the value of attribute style.
7 8 9 |
# File 'lib/visual_width/table.rb', line 7 def style @style end |
Instance Method Details
#draw(*args) ⇒ Object
54 55 56 57 |
# File 'lib/visual_width/table.rb', line 54 def draw(*args) warn "draw() is deprecated. Use render() instead." render(*args) end |
#render(rows, header: nil, output: "") ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/visual_width/table.rb', line 16 def render(rows, header: nil, output: "") if @needs_wrap default_style = {} rows = rows.map do |row| i = 0 row.map do |cell| cell = "#{cell}" width = (@style[i] || default_style)[:width] i += 1 if width wrap(cell, width) else cell end end end end max_widths = calc_max_widths(rows) h = header || @header style_header = [] if h max_widths = calc_max_widths([h]) .zip(max_widths) .map { |values| values.max } h.length.times do |i| style = @style[i] || {} style_header << style.merge(align: :center) end end draw_header(output, max_widths, style_header, h) rows.each do |row| draw_row(output, max_widths, @style, row) end line(output, max_widths) output end |