Class: Generator

Inherits:
Object show all
Defined in:
lib/amp/support/generator.rb

Overview

Generic generator. woo. Implement generator_loop to make a concrete subclass.

Allows you to create an object that lazily generates values and yields them when the next() method is called.

Direct Known Subclasses

Amp::Graphs::AncestorGenerator

Instance Method Summary collapse

Constructor Details

#initializeGenerator

Generic initializer for a Generator. If you subclass, you must caller super to initialize the continuation ivars.



31
32
33
34
# File 'lib/amp/support/generator.rb', line 31

def initialize
 @current_context = nil
 reset
end

Instance Method Details

#nextObject

Runs the next iteration of the generator. Uses continuations to jump across the stack all willy-nilly like.

Returns:

  • (Object)

    the next generated object.



41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/amp/support/generator.rb', line 41

def next
  # by setting @current_context to +here+, when @current_context is called, next() will
  # return to its caller.
  callcc do |here|
    @current_context = here
    if @yield_context
      # Run next iteration of the running loop
      @yield_context.call
    else
      # Start the loop
      generator_loop
   end
  end
end

#resetObject

Resets the generator from the beginning



58
59
60
# File 'lib/amp/support/generator.rb', line 58

def reset
  @yield_context = nil
end