提交 346ccf37 编写于 作者: D Dmitry Vorotilin

Kernel#capture replaced by version which can catch output from subprocesses

上级 c7e233ce
## Rails 4.0.0 (unreleased) ##
* Kernel#capture can catch output from subprocesses *Dmitry Vorotilin*
* Make callstack attribute optional in
ActiveSupport::Deprecation::Reporting methods `warn` and `deprecation_warning`
......
require 'rbconfig'
require 'tempfile'
module Kernel
# Sets $VERBOSE to nil for the duration of the block and back to its original
......@@ -66,19 +67,33 @@ def suppress(*exception_classes)
# Captures the given stream and returns it:
#
# stream = capture(:stdout) { puts 'Cool' }
# stream # => "Cool\n"
# 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"
def capture(stream)
begin
stream = stream.to_s
eval "$#{stream} = StringIO.new"
yield
result = eval("$#{stream}").string
ensure
eval("$#{stream} = #{stream.upcase}")
end
stream = stream.to_s
captured_stream = Tempfile.new(stream)
stream_io = eval("$#{stream}")
origin_stream = stream_io.dup
stream_io.reopen(captured_stream)
yield
result
stream_io.rewind
return captured_stream.read
ensure
captured_stream.unlink
stream_io.reopen(origin_stream)
end
alias :silence :capture
......
......@@ -51,6 +51,8 @@ class << o; @x = 1; end
def test_capture
assert_equal 'STDERR', capture(:stderr) { $stderr.print 'STDERR' }
assert_equal 'STDOUT', capture(:stdout) { print 'STDOUT' }
assert_equal "STDERR\n", capture(:stderr) { system('echo STDERR 1>&2') }
assert_equal "STDOUT\n", capture(:stdout) { system('echo STDOUT') }
end
end
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册