class Consumer

A class implementing consumer coroutines

A Consumer can be created by the following methods:

See Object#consum_for for an explanation of the basic concepts.

Attributes

result[R]

After the consumer has terminated (which may have happened in response to #close), result contains the value returned by the consumer.

Public Class Methods

new { |yielder| ... } → consumer click to toggle source

Creates a new Consumer coroutine, which can be used as a Sink.

The block is called immediately with a “yielder” object as parameter. yielder can be used to retrieve a value from the consumption context by calling its await method.

consum = Consumer.new do |y|
  a = y.await
  b = y.await
  "#{a} + #{b} = #{a + b}"
end

consum << 42 << 24
consum.close  # => "42 + 24 = 66"
# File lib/coroutines/base.rb, line 53
def initialize(&block)
        @fiber = Fiber.new(&block)
        @result = nil

        self << Yielder.new
end

Public Instance Methods

consumer << obj → consumer click to toggle source

Feeds obj as an input to the consumer.

# File lib/coroutines/base.rb, line 73
def <<(obj)
        raise StopIteration unless @fiber.alive?
        value = @fiber.resume(obj)
        @result = value unless @fiber.alive?
        self
end
close → obj click to toggle source

Terminate the consumer by raising StopIteration at the point where it last requested an input value. obj is the return value of the consumer.

# File lib/coroutines/base.rb, line 86
def close
        @result = @fiber.raise StopIteration if @fiber.alive?
        return @result
rescue StopIteration
        return @result
end
inspect() click to toggle source
# File lib/coroutines/base.rb, line 60
def inspect
        status = if @fiber.alive? then "running" else @result.inspect end
        "#<Consumer: 0x#{object_id.to_s(16)} (#{status})>"
end