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 
Sign up to request clarification or add additional context in comments.

Comments

2
require 'stringio' def capture_stderr old, $stderr = $stderr, StringIO.new result = yield [result, $stderr.string] ensure $stderr = old end 

Comments

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 Comment

Can it be redirected to some Ruby internal IO rather than an external file?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.