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.



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

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:



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

def children
  @children
end

#dataObject? (readonly)

Returns Associated data.

Returns:

  • (Object, nil)

    Associated data



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

def data
  @data
end

#expandedBoolean

Returns Expanded state.

Returns:

  • (Boolean)

    Expanded state



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

def expanded
  @expanded
end

#labelString (readonly)

Returns Node label.

Returns:

  • (String)

    Node label



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

def label
  @label
end

#styleStyle? (readonly)

Returns Label style.

Returns:

  • (Style, nil)

    Label style



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

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:



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

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

#child_countInteger

Returns Number of children.

Returns:

  • (Integer)

    Number of children



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

def child_count
  @children.length
end

#descendant_countInteger

Returns Total descendant count.

Returns:

  • (Integer)

    Total descendant count



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

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



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

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



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

def leaf?
  @children.empty?
end