Class: Async::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/async/node.rb

Overview

Represents a node in a tree, used for nested Task instances.

Direct Known Subclasses

Reactor, Task

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parent = nil) ⇒ Node

Create a new node in the tree.

Parameters:

  • parent (Node, nil) (defaults to: nil)

    This node will attach to the given parent.



28
29
30
31
32
33
34
35
36
37
38
# File 'lib/async/node.rb', line 28

def initialize(parent = nil)
  @children = Set.new
  @parent = nil
  
  @annotation = nil
  @object_name = nil
  
  if parent
    self.parent = parent
  end
end

Instance Attribute Details

#annotationObject (readonly)

A useful identifier for the current node.



47
48
49
# File 'lib/async/node.rb', line 47

def annotation
  @annotation
end

#childrenObject (readonly)



44
45
46
# File 'lib/async/node.rb', line 44

def children
  @children
end

#parentObject



41
42
43
# File 'lib/async/node.rb', line 41

def parent
  @parent
end

Instance Method Details

#annotate(annotation) ⇒ Object



49
50
51
52
53
54
55
56
57
58
# File 'lib/async/node.rb', line 49

def annotate(annotation)
  if block_given?
    previous_annotation = @annotation
    @annotation = annotation
    yield
    @annotation = previous_annotation
  else
    @annotation = annotation
  end
end

#consumeObject

If the node has a parent, and is #finished?, then remove this node from the parent.



102
103
104
105
106
107
108
# File 'lib/async/node.rb', line 102

def consume
  if @parent and finished?
    @parent.reap(self)
    @parent.consume
    @parent = nil
  end
end

#descriptionObject



60
61
62
63
64
65
66
67
68
# File 'lib/async/node.rb', line 60

def description
  @object_name ||= "#{self.class}:0x#{object_id.to_s(16)}"
  
  if @annotation
    "#{@object_name} #{@annotation}"
  else
    @object_name
  end
end

#finished?Boolean

Whether the node can be consumed safely. By default, checks if the children set is empty.

Returns:

  • (Boolean)


96
97
98
# File 'lib/async/node.rb', line 96

def finished?
  @children.empty?
end


126
127
128
129
130
# File 'lib/async/node.rb', line 126

def print_hierarchy(out = $stdout)
  self.traverse do |node, level|
    out.puts "#{"\t" * level}#{node}"
  end
end

#reap(child) ⇒ Object

Remove a given child node.

Parameters:



112
113
114
# File 'lib/async/node.rb', line 112

def reap(child)
  @children.delete(child)
end

#to_sObject



70
71
72
# File 'lib/async/node.rb', line 70

def to_s
  "\#<#{description}>"
end

#traverse(level = 0) {|node, level| ... } ⇒ Object

Traverse the tree.

Yields:

  • (node, level)

    The node and the level relative to the given root.



118
119
120
121
122
123
124
# File 'lib/async/node.rb', line 118

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