Thursday 3 December 2009

Reassigning STDERR without warning messages

There are times when some library feels that it is necessary to print a warning you have no interest in to STDERR (the constant assigned to the stderr stream on Ruby). All well and good until you run cron jobs. Then you can an email each time. So lets reassign STDERR, do something that will try and write to STDERR and then put it back. Without generating any unnecessary messages.

# Get a copy of $stderr so we can restore it later
$stderr_backup = $stderr.dup

# Send everything for $stderr to /dev/null
$stderr.reopen("/dev/null", "w")

# Now do something that will write to $stderr or STDERR

# Restore the original $stderr. Note that this will result in a warning
# being sent to the existing $stderr which we will not see
STDERR = $stderr_backup.dup

# Now restore the global $stderr
$stderr = $stderr_backup.dup

Swap the last two lines round and you will get a warning message printed that you are reassigning a constant. Miss out the last line and STDERR.puts will write to the stderr stream but $stderr.puts will still be writing to /dev/null

No comments:

Post a Comment