Class: Moonshot::UnicodeTable

Inherits:
Object
  • Object
show all
Defined in:
lib/moonshot/unicode_table.rb

Overview

A class for drawing hierarchical information using unicode lines.

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ UnicodeTable

Returns a new instance of UnicodeTable.



8
9
10
11
12
# File 'lib/moonshot/unicode_table.rb', line 8

def initialize(name)
  @name = name
  @lines = []
  @children = []
end

Instance Method Details

#add_leaf(name) ⇒ Object



14
15
16
17
18
# File 'lib/moonshot/unicode_table.rb', line 14

def add_leaf(name)
  new_leaf = UnicodeTable.new(name)
  @children << new_leaf
  new_leaf
end

#add_line(line) ⇒ Object



20
21
22
23
# File 'lib/moonshot/unicode_table.rb', line 20

def add_line(line)
  @lines << line
  self
end

#add_table(table) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/moonshot/unicode_table.rb', line 25

def add_table(table)
  # Calculate widths
  widths = []
  table.each do |line|
    line.each_with_index do |col, i|
      col = '?' unless col.respond_to?(:length)
      widths[i] = [widths[i] || 0, col.length].max
    end
  end

  format = widths.collect { |n| "%-#{n}s" }.join(' ') << "\n"
  table.each { |line| add_line(format(format, *line)) }
end

#draw(depth = 1, first = true) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/moonshot/unicode_table.rb', line 39

def draw(depth = 1, first = true)
  print first ? '' : ''
  print '' * depth
  puts ' ' << @name.light_black
  @lines = [''] + @lines + ['']
  @lines.each do |line|
    puts '' << (' ' * depth) << line
  end
  @children.each do |child|
    child.draw(depth + 1, false)
  end
end

#draw_childrenObject

Draw all children at the same level, for having multiple top-level peer leaves.



54
55
56
57
58
59
60
61
# File 'lib/moonshot/unicode_table.rb', line 54

def draw_children
  first = true
  @children.each do |child|
    child.draw(1, first)
    first = false
  end
  puts '└──'
end