Class: Rich::TreeNode

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

Overview

A node in a tree structure

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(label, style: nil, data: nil, expanded: true) ⇒ TreeNode

Returns a new instance of TreeNode.



63
64
65
66
67
68
69
# File 'lib/rich/tree.rb', line 63

def initialize(label, style: nil, data: nil, expanded: true)
  @label = label.to_s
  @style = style.is_a?(String) ? Style.parse(style) : style
  @children = []
  @data = data
  @expanded = expanded
end

Instance Attribute Details

#childrenArray<TreeNode> (readonly)

Returns Child nodes.

Returns:



55
56
57
# File 'lib/rich/tree.rb', line 55

def children
  @children
end

#dataObject? (readonly)

Returns Associated data.

Returns:

  • (Object, nil)

    Associated data



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

def data
  @data
end

#expandedBoolean

Returns Expanded state.

Returns:

  • (Boolean)

    Expanded state



61
62
63
# File 'lib/rich/tree.rb', line 61

def expanded
  @expanded
end

#labelString (readonly)

Returns Node label.

Returns:

  • (String)

    Node label



49
50
51
# File 'lib/rich/tree.rb', line 49

def label
  @label
end

#styleStyle? (readonly)

Returns Label style.

Returns:

  • (Style, nil)

    Label style



52
53
54
# File 'lib/rich/tree.rb', line 52

def style
  @style
end

Instance Method Details

#add(label, **kwargs) ⇒ TreeNode

Add a child node

Parameters:

  • label (String)

    Child label

  • kwargs (Hash)

    Node options

Returns:



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

def add(label, **kwargs)
  child = TreeNode.new(label, **kwargs)
  @children << child
  child
end

#child_countInteger

Returns Number of children.

Returns:

  • (Integer)

    Number of children



87
88
89
# File 'lib/rich/tree.rb', line 87

def child_count
  @children.length
end

#descendant_countInteger

Returns Total descendant count.

Returns:

  • (Integer)

    Total descendant count



92
93
94
# File 'lib/rich/tree.rb', line 92

def descendant_count
  @children.sum { |c| 1 + c.descendant_count }
end

#each_descendant(depth = 0) {|TreeNode, Integer| ... } ⇒ Object

Iterate through all descendants

Yields:

  • (TreeNode, Integer)

    Each node and its depth



98
99
100
101
102
103
# File 'lib/rich/tree.rb', line 98

def each_descendant(depth = 0, &block)
  yield(self, depth)
  @children.each do |child|
    child.each_descendant(depth + 1, &block)
  end
end

#leaf?Boolean

Returns True if node has children.

Returns:

  • (Boolean)

    True if node has children



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

def leaf?
  @children.empty?
end