Module: SilentStream::Extracted
- Defined in:
- lib/silent_stream.rb
Overview
Constant Summary collapse
- SILENT_STREAM_NULL_DEVICE =
if defined?(IO::NULL) IO::NULL else Gem.win_platform? ? "NUL:" : "/dev/null" end
Instance Method Summary collapse
-
#capture(stream) ⇒ Object
Captures the given stream and returns it:.
-
#quietly(&block) ⇒ Object
Silences both STDOUT and STDERR, even for subprocesses.
-
#silence_stderr(&block) ⇒ Object
This method is not thread-safe.
-
#silence_stream(stream) ⇒ Object
Silences any stream for the duration of the block.
Instance Method Details
#capture(stream) ⇒ Object
Captures the given stream and returns it:
stream = capture(:stdout) { puts 'notice' }
stream # => "notice\n"
stream = capture(:stderr) { warn 'error' }
stream # => "error\n"
even for subprocesses:
stream = capture(:stdout) { system('echo notice') }
stream # => "notice\n"
stream = capture(:stderr) { system('echo error 1>&2') }
stream # => "error\n"
This method is not thread-safe.
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 |
# File 'lib/silent_stream.rb', line 111 def capture(stream) stream = stream.to_s captured_stream = Tempfile.new(stream) stream_io = eval("$#{stream}") origin_stream = stream_io.dup stream_io.reopen(captured_stream) yield stream_io.rewind captured_stream.read ensure captured_stream.close captured_stream.unlink stream_io.reopen(origin_stream) end |
#quietly(&block) ⇒ Object
Silences both STDOUT and STDERR, even for subprocesses.
quietly { system 'bundle install' }
This method is not thread-safe.
136 137 138 139 140 |
# File 'lib/silent_stream.rb', line 136 def quietly(&block) silence_stream(STDOUT) do silence_stream(STDERR, &block) end end |
#silence_stderr(&block) ⇒ Object
This method is not thread-safe.
67 68 69 |
# File 'lib/silent_stream.rb', line 67 def silence_stderr(&block) silence_stream(STDERR, &block) end |
#silence_stream(stream) ⇒ Object
Silences any stream for the duration of the block.
silence_stream(STDOUT) do
puts 'This will never be seen'
end
puts 'But this will'
This method is not thread-safe.
80 81 82 83 84 85 86 87 88 89 90 91 92 |
# File 'lib/silent_stream.rb', line 80 def silence_stream(stream) old_stream = stream.dup begin stream.reopen(SILENT_STREAM_NULL_DEVICE, "a+") rescue Exception => e stream.puts "[SilentStream] Unable to silence. #{e.class}: #{e.}" end stream.sync = true yield ensure stream.reopen(old_stream) old_stream.close end |