module Captio::Scheduler

Public Instance Methods

schedule_capture_fiber(stream, emitter) click to toggle source

Factory method that creates a Fiber that captures an output stream.

Emits the following events

:start           =>  When the stream is captured
:capture_line    =>  When a line written to the stream is captured
:capture_block   =>  Everything that was captured (always emitted even if
                     no text was captured)
:restore         =>  When the stream is restored to the original
# File lib/captio/scheduler.rb, line 28
def schedule_capture_fiber(stream, emitter)
  Fiber.new do
    old_stream = stream.clone

    pipe_read, pipe_write = IO.pipe
    pipe_read.sync = true

    captured_text = ''
    emit = lambda do |event, *args|
      begin
        emitter.emit(event, *args) if emitter.respond_to?(:emit)
      rescue Exception => e
        emitter.emit(:error, e)
      end
    end

    stream_reader = schedule_reader_thread pipe_read do |line|
      captured_text << line
      emit.(:capture_line, line)
    end

    stream.reopen pipe_write

    emit.(:start)
    Fiber.yield

    stream.reopen old_stream
    pipe_write.close

    stream_reader.join

    emit.(:capture_block, captured_text)
    emit.(:restore)
  end
end
schedule_reader_thread(pipe_read_channel) { |readline| ... } click to toggle source

Factory method that creates a thread that awaits for lines to be written to a pipe read channel and passing them to a given block. It exists when the pipe is closed.

# File lib/captio/scheduler.rb, line 9
def schedule_reader_thread(pipe_read_channel)
  Thread.new do
    begin
      loop do
        yield pipe_read_channel.readline
      end
    rescue EOFError
    end
  end
end