Class: FiberSpace::FiberChain

Inherits:
Object
  • Object
show all
Defined in:
lib/fiber_space/chain.rb

Overview

A FiberChain encapsulates and organizes a SortedSet of Fiber or FiberContainer objects. It facilitates the sequential execution of Fiber and FiberContainer objects.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*containers, continuous: false) ⇒ FiberChain

Constructs a new FiberChain

Parameters:

  • containers (Array)

    collection of Fibers or FiberContainers.



11
12
13
14
15
16
# File 'lib/fiber_space/chain.rb', line 11

def initialize(*containers, continuous: false)
  @continuous_mode = continuous
  @stack = SortedSet.new
  @closed = false
  containers.each { |fiber_container| register(fiber_container) }
end

Instance Attribute Details

#closedBoolean

Returns has the chain closed?.

Returns:

  • (Boolean)

    has the chain closed?



7
8
9
# File 'lib/fiber_space/chain.rb', line 7

def closed
  @closed
end

Instance Method Details

#complete?Boolean

Has all elements of the FiberChain#stack completed execution?

Returns:

  • (Boolean)


73
74
75
76
77
78
79
# File 'lib/fiber_space/chain.rb', line 73

def complete?
  if @continuous_mode
    @stack.all?(&:completed?) || @closed
  else
    @stack.empty? || @stack.all?(&:completed?) || @closed
  end
end

#executeObject

Begins executing all items within the FiberChain#stack until all items are complete or the stack is empty.



44
45
46
47
48
49
50
51
52
53
# File 'lib/fiber_space/chain.rb', line 44

def execute
  if @continuous_mode
    loop do
      iterate
      break if @closed
    end
  else
    iterate until complete?
  end
end

#iterateObject

Performs a single iteration of execution on the FiberChain#stack.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/fiber_space/chain.rb', line 19

def iterate
  @worker ||= Fiber.new do
    loop do
      break if !@continuous_mode && complete?

      if @stack.any?(&:completed?)
        @stack.delete_if(&:completed?)
        prepare
      end

      if @continuous_mode
        Fiber.yield(@stack.each(&:resume))
      else
        Fiber.yield(@stack.first&.resume)
      end
    rescue StandardError => e
      puts 'An error occurred during FiberChain#iterate!'
      puts e.message
      puts e.backtrace&.join("\n")
    end
  end
  @worker.resume
end

#lengthInteger

The length of the FiberChain#stack

Returns:

  • (Integer)

    the length



67
68
69
# File 'lib/fiber_space/chain.rb', line 67

def length
  @stack.length
end

#register(item) ⇒ Object

Pushes an item to the FiberChain#stack

Parameters:



57
58
59
60
61
62
63
# File 'lib/fiber_space/chain.rb', line 57

def register(item)
  @stack << case item
            when Fiber then FiberContainer.new(source: item)
            when FiberContainer then item
            else raise TypeError, 'Expecting Fiber or FiberContainer!'
            end
end