Class: TTY::Tree

Inherits:
Object
  • Object
show all
Defined in:
lib/tty/tree.rb,
lib/tty/tree/node.rb,
lib/tty/tree/version.rb,
lib/tty/tree/hash_walker.rb,
lib/tty/tree/path_walker.rb,
lib/tty/tree/number_renderer.rb,
lib/tty/tree/directory_renderer.rb

Defined Under Namespace

Classes: DirectoryRenderer, HashWalker, LeafNode, Node, NumberRenderer, PathWalker

Constant Summary collapse

VERSION =
"0.4.0"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data = nil, options = {}, &block) ⇒ Tree

Create a Tree

Parameters:

  • data (String, Dir, Hash) (defaults to: nil)

25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/tty/tree.rb', line 25

def initialize(data = nil, options = {}, &block)
  @data   = data ? data.dup.freeze : nil
  @walker = select_walker.new(options)
  @nodes  = []

  if @data
    @walker.traverse(data)
    @nodes = @walker.nodes
  end

  @nodes_stack = []

  instance_eval(&block) if block_given?

  freeze
end

Instance Attribute Details

#nodesObject (readonly)

The list of nodes in this tree.


18
19
20
# File 'lib/tty/tree.rb', line 18

def nodes
  @nodes
end

Class Method Details

.[](data) ⇒ Object


13
14
15
# File 'lib/tty/tree.rb', line 13

def self.[](data)
  new(data)
end

Instance Method Details

#leaf(name, &block) ⇒ Object

Add leaf node


82
83
84
# File 'lib/tty/tree.rb', line 82

def leaf(name, &block)
  node(name, LeafNode, &block)
end

#node(name, type = Node, &block) ⇒ Object

Add node to this tree.

Examples:

TTY::Tree.new do
  node '...' do
    node '...'
  end
end

Parameters:

  • name (Symbol, String)

    the name for the node

  • type (Node, LeafNode) (defaults to: Node)

    the type of node to add


58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/tty/tree.rb', line 58

def node(name, type = Node, &block)
  parent = @nodes_stack.empty? ? Node::ROOT : @nodes_stack.last
  level = [0, @nodes_stack.size - 1].max
  prefix = ':pipe' * level
  if parent.class == LeafNode
    prefix = ':space' * level
  end
  node = type.new(name, parent.full_path, prefix, @nodes_stack.size)
  @nodes << node

  return unless block_given?

  @nodes_stack << node
  if block.arity.zero?
    instance_eval(&block)
  else
    instance_eval(&(->(*_args) { block[node] }))
  end
  @nodes_stack.pop
end

#render(options = {}) ⇒ Object


87
88
89
90
91
# File 'lib/tty/tree.rb', line 87

def render(options = {})
  as = options.delete(:as) || :dir
  renderer = select_renderer(as).new(nodes, options)
  renderer.render
end