Class: Rich::TreeNode
- Inherits:
-
Object
- Object
- Rich::TreeNode
- Defined in:
- lib/rich/tree.rb
Overview
A node in a tree structure
Instance Attribute Summary collapse
-
#children ⇒ Array<TreeNode>
readonly
Child nodes.
-
#data ⇒ Object?
readonly
Associated data.
-
#expanded ⇒ Boolean
Expanded state.
-
#label ⇒ String
readonly
Node label.
-
#style ⇒ Style?
readonly
Label style.
Instance Method Summary collapse
-
#add(label, **kwargs) ⇒ TreeNode
Add a child node.
-
#child_count ⇒ Integer
Number of children.
-
#descendant_count ⇒ Integer
Total descendant count.
-
#each_descendant(depth = 0) {|TreeNode, Integer| ... } ⇒ Object
Iterate through all descendants.
-
#initialize(label, style: nil, data: nil, expanded: true) ⇒ TreeNode
constructor
A new instance of TreeNode.
-
#leaf? ⇒ Boolean
True if node has children.
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 = end |
Instance Attribute Details
#children ⇒ Array<TreeNode> (readonly)
Returns Child nodes.
56 57 58 |
# File 'lib/rich/tree.rb', line 56 def children @children end |
#data ⇒ Object? (readonly)
Returns Associated data.
59 60 61 |
# File 'lib/rich/tree.rb', line 59 def data @data end |
#expanded ⇒ Boolean
Returns Expanded state.
62 63 64 |
# File 'lib/rich/tree.rb', line 62 def @expanded end |
#label ⇒ String (readonly)
Returns Node label.
50 51 52 |
# File 'lib/rich/tree.rb', line 50 def label @label end |
#style ⇒ Style? (readonly)
Returns 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
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_count ⇒ Integer
Returns Number of children.
88 89 90 |
# File 'lib/rich/tree.rb', line 88 def child_count @children.length end |
#descendant_count ⇒ Integer
Returns 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
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.
83 84 85 |
# File 'lib/rich/tree.rb', line 83 def leaf? @children.empty? end |