Module: Kernel

Defined in:
lib/agile_utils/core_ext/kernel/reporting.rb

Instance Method Summary collapse

Instance Method Details

#capture(stream) ⇒ Object

From: ‘activesupport-4.1.0/lib/active_support/core_ext/kernel/reporting.rb

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"


20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/agile_utils/core_ext/kernel/reporting.rb', line 20

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
  return captured_stream.read
ensure
  captured_stream.close
  captured_stream.unlink
  stream_io.reopen(origin_stream)
end