Class: RubyRich::Tree

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

Defined Under Namespace

Classes: Node

Constant Summary collapse

TREE_CHARS =

树形结构显示的字符集

{
  default: {
    vertical: '│',
    horizontal: '─',
    branch: '├',
    last: '└',
    space: ' '
  },
  ascii: {
    vertical: '|',
    horizontal: '-',
    branch: '+',
    last: '+',
    space: ' '
  },
  rounded: {
    vertical: '│',
    horizontal: '─',
    branch: '├',
    last: '└',
    space: ' '
  },
  double: {
    vertical: '║',
    horizontal: '═',
    branch: '╠',
    last: '╚',
    space: ' '
  }
}.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root_name = 'Root', style: :default) ⇒ Tree

Returns a new instance of Tree.



68
69
70
71
72
# File 'lib/ruby_rich/tree.rb', line 68

def initialize(root_name = 'Root', style: :default)
  @root = Node.new(root_name)
  @style = style
  @chars = TREE_CHARS[@style] || TREE_CHARS[:default]
end

Instance Attribute Details

#rootObject (readonly)

Returns the value of attribute root.



66
67
68
# File 'lib/ruby_rich/tree.rb', line 66

def root
  @root
end

#styleObject (readonly)

Returns the value of attribute style.



66
67
68
# File 'lib/ruby_rich/tree.rb', line 66

def style
  @style
end

Class Method Details

.from_hash(hash, root_name = 'Root', style: :default) ⇒ Object

从哈希构建树



75
76
77
78
79
# File 'lib/ruby_rich/tree.rb', line 75

def self.from_hash(hash, root_name = 'Root', style: :default)
  tree = new(root_name, style: style)
  build_from_hash(tree.root, hash)
  tree
end

.from_paths(paths, root_name = 'Root', style: :default) ⇒ Object

从文件路径构建树



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/ruby_rich/tree.rb', line 82

def self.from_paths(paths, root_name = 'Root', style: :default)
  tree = new(root_name, style: style)
  
  paths.each do |path|
    parts = path.split('/')
    current_node = tree.root
    
    parts.each do |part|
      next if part.empty?
      
      # 查找是否已存在该子节点
      existing_child = current_node.children.find { |child| child.name == part }
      
      if existing_child
        current_node = existing_child
      else
        current_node = current_node.add(part)
      end
    end
  end
  
  tree
end

Instance Method Details

#add(name, data: nil) ⇒ Object

添加节点到根节点



107
108
109
# File 'lib/ruby_rich/tree.rb', line 107

def add(name, data: nil)
  @root.add(name, data: data)
end

#render(show_guides: true, colors: true) ⇒ Object

渲染树形结构



112
113
114
115
116
# File 'lib/ruby_rich/tree.rb', line 112

def render(show_guides: true, colors: true)
  lines = []
  render_node(@root, '', true, lines, show_guides, colors)
  lines.join("\n")
end

#to_sObject

渲染为字符串(别名)



119
120
121
# File 'lib/ruby_rich/tree.rb', line 119

def to_s
  render
end