Sha256: c417fbe603b8ddabb90608226590e151c46918c2dce5d7a82ee759ebe67b2cdf

Contents?: true

Size: 1.17 KB

Versions: 30

Compression:

Stored size: 1.17 KB

Contents

# Using fibers instead of enumerators leads to less coupling in the processor.
# @see https://practicingruby.com/articles/building-enumerable-and-enumerator?u=dc2ab0f9bb
require 'fiber'

module Pupa
  class Processor
    # A lazy enumerator.
    class Yielder
      # The given block should yield objects to add to the enumerator.
      def initialize
        @fiber = Fiber.new do
          yield
          raise StopIteration
        end
      end

      # Yields each object in the enumerator to the given block.
      def each
        if block_given?
          loop do
            yield self.next
          end
        else
          to_enum
        end
      end

      # Returns the next object in the enumerator, and moves the internal position
      # forward. When the position reaches the end, `StopIteration` is raised.
      def next
        if @fiber.alive?
          @fiber.resume
        else
          raise StopIteration
        end
      end

      # Returns a lazy enumerator.
      #
      # @return [Enumerator] a lazy enumerator
      def to_enum
        Enumerator.new do |y|
          loop do
            y << self.next
          end
        end
      end
    end
  end
end

Version data entries

30 entries across 30 versions & 1 rubygems

Version Path
pupa-0.2.4 lib/pupa/processor/yielder.rb
pupa-0.2.3 lib/pupa/processor/yielder.rb
pupa-0.2.2 lib/pupa/processor/yielder.rb
pupa-0.2.1 lib/pupa/processor/yielder.rb
pupa-0.2.0 lib/pupa/processor/yielder.rb
pupa-0.1.11 lib/pupa/processor/yielder.rb
pupa-0.1.10 lib/pupa/processor/yielder.rb
pupa-0.1.9 lib/pupa/processor/yielder.rb
pupa-0.1.8 lib/pupa/processor/yielder.rb
pupa-0.1.7 lib/pupa/processor/yielder.rb
pupa-0.1.6 lib/pupa/processor/yielder.rb
pupa-0.1.5 lib/pupa/processor/yielder.rb
pupa-0.1.4 lib/pupa/processor/yielder.rb
pupa-0.1.3 lib/pupa/processor/yielder.rb
pupa-0.1.2 lib/pupa/processor/yielder.rb
pupa-0.1.1 lib/pupa/processor/yielder.rb
pupa-0.1.0 lib/pupa/processor/yielder.rb
pupa-0.0.13 lib/pupa/processor/yielder.rb
pupa-0.0.12 lib/pupa/processor/yielder.rb
pupa-0.0.11 lib/pupa/processor/yielder.rb