class Mustermann::Visualizer::Tree

Represents a (sub)tree and at the same time a node in the tree.

Attributes

after[R]

@!visibility private

before[R]

@!visibility private

children[R]

@!visibility private

line[R]

@!visibility private

prefix_color[R]

@!visibility private

Public Class Methods

new(line, *children, prefix_color: :default, before: "", after: "") click to toggle source

@!visibility private

# File lib/mustermann/visualizer/tree.rb, line 11
def initialize(line, *children, prefix_color: :default, before: "", after: "")
  @line         = line
  @children     = children
  @prefix_color = prefix_color
  @before       = before
  @after        = after
end

Public Instance Methods

line_widths(offset = 0) click to toggle source

used for positioning {#after} @!visibility private

# File lib/mustermann/visualizer/tree.rb, line 21
def line_widths(offset = 0)
  child_widths = children.flat_map { |c| c.line_widths(offset + 2)  }
  width        = length(line + before) + offset
  [width, *child_widths]
end
render(first_prefix, prefix, width) click to toggle source

Renders tree, including nesting. @!visibility private

# File lib/mustermann/visualizer/tree.rb, line 35
def render(first_prefix, prefix, width)
  output = before + Hansi.render(prefix_color, first_prefix) + line
  output = ljust(output, width) + "  " + after + "\n"
  children[0..-2].each { |child| output += child.render(prefix + "├ ", prefix + "│ ", width) }
  output += children.last.render(prefix + "└ ", prefix + "  ", width) if children.last
  output
end
to_s() click to toggle source

Renders the tree. @return [String] rendered version of the tree

# File lib/mustermann/visualizer/tree.rb, line 29
def to_s
  render("", "", line_widths.max)
end

Private Instance Methods

deansi(string) click to toggle source

@!visibility private

# File lib/mustermann/visualizer/tree.rb, line 49
def deansi(string)
  string.gsub(/\e\[[^m]+m/, '')
end
length(string) click to toggle source

@!visibility private

# File lib/mustermann/visualizer/tree.rb, line 44
def length(string)
  deansi(string).length
end
ljust(string, width) click to toggle source

@!visibility private

# File lib/mustermann/visualizer/tree.rb, line 54
def ljust(string, width)
  missing = width - length(string)
  append  = missing > 0 ? " " * missing : ""
  string + append
end