Class: TreeNode

Inherits:
Object
  • Object
show all
Defined in:
lib/cli-tree.rb

Constant Summary collapse

VERSION =
'1.0.0'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, children = []) ⇒ TreeNode



6
7
8
9
# File 'lib/cli-tree.rb', line 6

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

Instance Attribute Details

#childrenObject

Returns the value of attribute children.



4
5
6
# File 'lib/cli-tree.rb', line 4

def children
  @children
end

#nameObject

Returns the value of attribute name.



4
5
6
# File 'lib/cli-tree.rb', line 4

def name
  @name
end

Instance Method Details



30
31
32
# File 'lib/cli-tree.rb', line 30

def print(stream: STDOUT, prefix: '')
  stream.puts render.map{|line| "#{prefix}#{line}\n"}
end

#renderObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/cli-tree.rb', line 11

def render
  lines = [@name]
  @children.each_with_index do |child, index|
    child_lines = child.render
    if index < @children.size - 1
      child_lines.each_with_index do |line, idx|
        prefix = (idx == 0) ? "├── " : "|   "
        lines << "#{prefix}#{line}"
      end
    else
      child_lines.each_with_index do |line, idx|
        prefix = (idx == 0) ? "└── " : "    "
        lines << "#{prefix}#{line}"
      end
    end
  end
  lines
end