Class: TreeNode

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

Constant Summary collapse

VERSION =
'1.1.0'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of TreeNode.



8
9
10
11
# File 'lib/cli-tree.rb', line 8

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

Instance Attribute Details

#childrenObject

Returns the value of attribute children.



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

def children
  @children
end

#nameObject

Returns the value of attribute name.



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

def name
  @name
end

Class Method Details

.from_h(hash) ⇒ Object



13
14
15
16
17
18
19
20
21
# File 'lib/cli-tree.rb', line 13

def TreeNode.from_h(hash)
  if hash.is_a?(Hash)
    raw_children = hash.has_key?(:children) ? hash[:children] : []
    children = raw_children.map{|ch| TreeNode.from_h(ch)}
    TreeNode.new hash[:name], children
  else
    TreeNode.new hash
  end
end

.from_json(json) ⇒ Object



23
24
25
26
# File 'lib/cli-tree.rb', line 23

def TreeNode.from_json(json)
  hash = JSON.parse json, symbolize_names: true
  TreeNode.from_h hash
end

Instance Method Details



58
59
60
# File 'lib/cli-tree.rb', line 58

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

#renderObject



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/cli-tree.rb', line 39

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

#to_hObject



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

def to_h
  {
    name: @name,
    children: @children.map{|node| node.to_h}
  }
end

#to_json(**kwargs) ⇒ Object



35
36
37
# File 'lib/cli-tree.rb', line 35

def to_json(**kwargs)
  JSON.generate(to_h, **kwargs)
end