Files
2025-09-29 00:52:08 +02:00

69 lines
1.8 KiB
Ruby
Executable File

#
# capturestdout.rb
# Capture StdOut from ruby functions/classes, e.g. TestCase messages.
#
# Author:: David Muir <david.muir@rockstarnorth.com>
# Date:: 30 January 2008
#
# References:
# * http://stefankst.net/2007/06/05/capture-standard-output-in-ruby/
#
#-----------------------------------------------------------------------------
# Uses
#-----------------------------------------------------------------------------
require 'pipeline/log/log'
require 'stringio'
module Pipeline
module OS
#
# == Description
# Yields Ruby block with stdout captured to a StringIO object and returns
# the resulting string.
#
# == Example Usage
# out = Pipeline::OS.capture_stdout do
# puts "Hello, World!"
# end
# puts out
#
def self.capture_stdout
rootlog = LogSystem::instance.rootlog
rootlog.debug( "Pipeline::OS.capture_stdout : capturing $stdout." )
# Save old $stdout IO stream, and create new String IO stream.
old_stdout = $stdout
out = StringIO.new()
# Set $stdout to our new StringIO stream.
$stdout = out
begin
# This invokes the calling scope's code block.
yield
rescue Exception => ex
rootlog.error( "Pipeline::OS.capture_stdout exception: #{ex.message}." )
rootlog.error( " Backtrace: " )
ex.backtrace.each do |msg|
rootlog.error( " #{msg}" )
end
ensure
# Ensure that we restore $stdout to previous IO stream.
rootlog.debug( "Pipeline::OS.capture_stdout : restoring $stdout." )
$stdout = old_stdout
end
out.string
end
end # OS module
end # Pipeline module
# End of capturestdout.rb