Class: VisualWidth::Table

Inherits:
Object
  • Object
show all
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

Instance Method Summary collapse

Methods included from VisualWidth

count, each_width, measure, truncate

Constructor Details

#initialize(header: nil, style: [], east_asian: VisualWidth::EAST_ASIAN) ⇒ Table

Returns a new instance of Table.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/visual_width/table.rb', line 9

def initialize(header: nil, style: [], east_asian: VisualWidth::EAST_ASIAN)
  @header = header
  @style  = style.clone
  @east_asian = east_asian
  @padding = ' '

  if header
    header.length.times do |i|
      @style[i] ||= {}
    end
  end

  widths = @style.map { |s| s[:width] }
  @needs_wrap = widths.any?
  if header
    @header_widths = calc_max_widths([header])
  end
end

Instance Attribute Details

#headerObject

Returns the value of attribute header.



7
8
9
# File 'lib/visual_width/table.rb', line 7

def header
  @header
end

#styleObject

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



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

def draw(*args)
  warn "draw() is deprecated. Use render() instead."
  render(*args)
end

#render(rows, output: "") ⇒ Object



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
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/visual_width/table.rb', line 28

def render(rows, output: "")
  if @needs_wrap
    rows = rows.map do |row|
      i = 0
      row.map do |cell|
        cell = "#{cell}"
        style = (@style[i] ||= {})
        width = style[:width]
        i += 1
        if width
          wrap(cell, width)
        else
          cell
        end
      end
    end
  end
  max_widths = calc_max_widths(rows)
  if @header
    header_style = []
    max_widths = @header_widths
      .zip(max_widths)
      .map { |values| values.max }
    @header.length.times do |i|
      style = (@style[i] ||= {})
      header_style << style.merge(align: :center)
    end
    draw_header(output, max_widths, header_style, @header)
  else
    line(output, max_widths)
  end

  rows.each do |row|
    draw_row(output, max_widths, @style, row)
  end
  line(output, max_widths)
  output
end