Created
October 2, 2018 17:07
-
-
Save mtking2/c9212b79e0b7cf2bf677728347ebb4ad to your computer and use it in GitHub Desktop.
Suppress Output Ruby wrapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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