Class: TreeNode
- Inherits:
-
Object
- Object
- TreeNode
- Defined in:
- lib/cli-tree.rb
Constant Summary collapse
- VERSION =
'1.1.0'
Instance Attribute Summary collapse
-
#children ⇒ Object
Returns the value of attribute children.
-
#name ⇒ Object
Returns the value of attribute name.
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(name, children = []) ⇒ TreeNode
constructor
A new instance of TreeNode.
- #print(stream: STDOUT, prefix: '') ⇒ Object
- #render ⇒ Object
- #to_h ⇒ Object
- #to_json(**kwargs) ⇒ Object
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
#children ⇒ Object
Returns the value of attribute children.
6 7 8 |
# File 'lib/cli-tree.rb', line 6 def children @children end |
#name ⇒ Object
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 |
Instance Method Details
#print(stream: STDOUT, prefix: '') ⇒ Object
58 59 60 |
# File 'lib/cli-tree.rb', line 58 def print(stream: STDOUT, prefix: '') stream.puts render.map{|line| "#{prefix}#{line}\n"} end |
#render ⇒ Object
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_h ⇒ Object
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 |