Skip to content

Instantly share code, notes, and snippets.

@mtking2
Created October 2, 2018 17:07
Show Gist options
  • Save mtking2/c9212b79e0b7cf2bf677728347ebb4ad to your computer and use it in GitHub Desktop.
Save mtking2/c9212b79e0b7cf2bf677728347ebb4ad to your computer and use it in GitHub Desktop.
Suppress Output Ruby wrapper
# This wrapper method helps to suppress any unnecessary output
# from stdout or stderr when executing a block of code.
#
# Reminder: any print/puts statements within the given block will
# also be suppressed since they go to stdout.
#
# usage: suppress_output <block>
#
# eg:
# suppress_output { ... }
# or
# suppress_output do
# ...
# end
#
def suppress_output
begin
original_stderr = $stderr.clone
original_stdout = $stdout.clone
$stderr.reopen(File.new('/dev/null', 'w'))
$stdout.reopen(File.new('/dev/null', 'w'))
retval = yield
rescue => e
$stdout.reopen(original_stdout)
$stderr.reopen(original_stderr)
raise e
ensure
$stdout.reopen(original_stdout)
$stderr.reopen(original_stderr)
end
retval
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment