1

Is there a way to capture the warnings, something like rescue for exceptions? I do not want to simply disable the warnings (by doing $VERBOSE = nil) but want to capture the content of the warning messages during run time.

3 Answers 3

2

You can redirect stderr to a StringIO object to capture the warnings output in a string:

require 'stringio'

old_stderr = $stderr
$stderr = StringIO.new
Foo = 1
Foo = 2 # generates a warning
puts $stderr.string # prints the warning
$stderr = old_stderr
2
require 'stringio'

def capture_stderr
  old, $stderr = $stderr, StringIO.new
  result = yield
  [result, $stderr.string]
ensure
  $stderr = old
end
1

This is kinda ugly because you will be writing to files and you might not have permission to write to them, and it will hide ALL output to $stderr, not just the warnings, but it works:

$stderr.reopen("errors.txt")
MyConst = 4
MyConst = 5   # generates a warning on the standard error output
$stderr.reopen("errors2.txt")
puts "The following errors happened:"
puts File.read("errors.txt")
1
  • Can it be redirected to some Ruby internal IO rather than an external file?
    – sawa
    Oct 6, 2012 at 17:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.