Sometimes external libraries send warning or console output without asking in Ruby. Very rude! It turns out there is a nice library out there that helps with this problem - and the good news is that this library is already built right into Rails so if you’re developing with this framework you have this tool at your fingertips.
The module that provides this functionality is located in the Facets library. You only need to install this module if you are running Ruby without Rails. The module provides functionality so that you can easily suppress warning messages, errors or standard output. In fact you can use the tool to suppress writing to any stream, so conceivably you could prevent a library from actually writing to any stream-based resource (like a file).
Using the library is easy. Let’s say we have a Poorly Behaved Library module method called PBL::rude_warnings - we want to suppress any warning messages that it emits. Assuming also that you have the Kernel extensions properly installed (via Rails or manually):
Kernel::silence_warnings {PBL::rude_warnings}
This nicely quiets this library down. I find it especially useful to shut up libraries that emit during my unit tests. I want unit tests to be very quiet so that anything that pops up is notable and requires attention. Finally let’s look at how we can silence output to standard out (STDOUT) in Ruby. This code is lifted from the facets core library:
silence_stream(STDOUT) do
puts 'This will never be seen'
end
puts 'But this will'
If you prefer to redirect your STDOUT or other stream to a file, that is easily accomplished using code inspired from the Facets lib:
f = File::open('/tmp/log.log', 'w') begin orig_std_out = STDOUT.clone STDOUT.reopen(f) puts 'prints to file' ensure STDOUT.reopen(orig_std_out) puts 'prints to console again' end