class TreeNode

Constants

VERSION

Attributes

children[RW]
name[RW]

Public Class Methods

from_h(hash) click to toggle source
# 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) click to toggle source
# File lib/cli-tree.rb, line 23
def TreeNode.from_json(json)
  hash = JSON.parse json, symbolize_names: true
  TreeNode.from_h hash
end
new(name, children = []) click to toggle source
# File lib/cli-tree.rb, line 8
def initialize(name, children = [])
  @name = name
  @children = children
end

Public Instance Methods

print(stream: STDOUT, prefix: '') click to toggle source
render() click to toggle source
# 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() click to toggle source
# File lib/cli-tree.rb, line 28
def to_h
  {
    name: @name,
    children: @children.map{|node| node.to_h}
  }
end
to_json(**kwargs) click to toggle source
# File lib/cli-tree.rb, line 35
def to_json(**kwargs)
  JSON.generate(to_h, **kwargs)
end