f = File::open('console.log', 'w') begin temp_std_out = STDOUT.clone STDOUT.reopen(f) puts 'this will go to the file' ensure STDOUT.reopen(temp_std_out) puts 'this will go to the screen' end
A computer science website with some additional odds and ends as well as my favorite programming language Ruby and the popular Ruby web framework Ruby on Rails(RoR).
Sunday, May 16, 2010
Redirecting Console Output: File
If you have occasion to require to redirect some console output produced by your code to a file, you can accomplish this with a few lines of code like so:
Friday, May 14, 2010
Suppressing Console Output
There are times when suppressing console output would be very useful. Lets say you have a class your writing a spec for which produces allot of console output. When your spec runs, the output can be very noisy. In such a case you can do the following:
describe NoisyClass do before :all do @noisy = NoisyClass.new silence_stream(STDOUT) do #The console output in this block #will never be seen @noisy.generate_console_output end end end
The 'silence_stream' method is defined in 'vendor/rails/activesupport/lib/active_support/core_ext/kernel/reporting.rb' and is used to silence any stream for the duration of the block.
Subscribe to:
Posts (Atom)