module TaskJuggler::StdIoWrapper

This module provides just one method to run the passed block. It will capture all content that will be send to $stdout and $stderr by the block. I can also feed the String provided by stdIn to $stdin of the block.

Constants

Results

Public Instance Methods

stdIoWrapper(stdIn = nil) { || ... } click to toggle source
# File lib/taskjuggler/StdIoWrapper.rb, line 23
def stdIoWrapper(stdIn = nil)
  # Save the old $stdout and $stderr and replace them with StringIO
  # objects to capture the output.
  oldStdOut = $stdout
  oldStdErr = $stderr
  $stdout = (out = StringIO.new)
  $stderr = (err = StringIO.new)

  # If the caller provided a String to feed into $stdin, we replace that
  # as well.
  if stdIn
    oldStdIn = $stdin
    $stdin = StringIO.new(stdIn)
  end

  begin
    # Call the block with the hooked up IOs.
    res = yield
  rescue RuntimeError
    # Blocks that are called this way usually return 0 on success and 1 on
    # errors.
    res = 1
  ensure
    # Restore the stdio channels no matter what.
    $stdout = oldStdOut
    $stderr = oldStdErr
    $stdin = oldStdIn if stdIn
  end

  # Return the return value of the block and the $stdout and $stderr
  # captures.
  Results.new(res, out.string, err.string)
end