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.
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 = end |
Instance Attribute Details
#children ⇒ Array<TreeNode> (readonly)
Returns Child nodes.
55 56 57 |
# File 'lib/rich/tree.rb', line 55 def children @children end |
#data ⇒ Object? (readonly)
Returns Associated data.
58 59 60 |
# File 'lib/rich/tree.rb', line 58 def data @data end |
#expanded ⇒ Boolean
Returns Expanded state.
61 62 63 |
# File 'lib/rich/tree.rb', line 61 def @expanded end |
#label ⇒ String (readonly)
Returns Node label.
49 50 51 |
# File 'lib/rich/tree.rb', line 49 def label @label end |
#style ⇒ Style? (readonly)
Returns 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
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_count ⇒ Integer
Returns Number of children.
87 88 89 |
# File 'lib/rich/tree.rb', line 87 def child_count @children.length end |
#descendant_count ⇒ Integer
Returns 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
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.
82 83 84 |
# File 'lib/rich/tree.rb', line 82 def leaf? @children.empty? end |