diff options
author | Krekoten' Marjan <krekoten@gmail.com> | 2010-09-16 19:03:55 +0300 |
---|---|---|
committer | José Valim <jose.valim@gmail.com> | 2010-09-18 20:49:36 +0200 |
commit | d4fa120671e989eecb71c14647dd2051d28de4a5 (patch) | |
tree | e5b9e768a4661dbac8c5f895b85d240be094aa4f /activesupport | |
parent | 76266a818449c732440e7e2ef4de8442ac6af891 (diff) | |
download | rails-d4fa120671e989eecb71c14647dd2051d28de4a5.tar.gz rails-d4fa120671e989eecb71c14647dd2051d28de4a5.tar.bz2 rails-d4fa120671e989eecb71c14647dd2051d28de4a5.zip |
Move capture to Kernel. [#5641 state:resolved]
Diffstat (limited to 'activesupport')
-rw-r--r-- | activesupport/lib/active_support/core_ext/kernel/reporting.rb | 19 | ||||
-rw-r--r-- | activesupport/test/core_ext/kernel_test.rb | 5 |
2 files changed, 24 insertions, 0 deletions
diff --git a/activesupport/lib/active_support/core_ext/kernel/reporting.rb b/activesupport/lib/active_support/core_ext/kernel/reporting.rb index 5105c40e4d..37a827123a 100644 --- a/activesupport/lib/active_support/core_ext/kernel/reporting.rb +++ b/activesupport/lib/active_support/core_ext/kernel/reporting.rb @@ -59,4 +59,23 @@ module Kernel raise unless exception_classes.any? { |cls| e.kind_of?(cls) } end end + + # Captures the given stream and returns it: + # + # stream = capture(:stdout){ puts "Cool" } + # stream # => "Cool\n" + # + def capture(stream) + begin + stream = stream.to_s + eval "$#{stream} = StringIO.new" + yield + result = eval("$#{stream}").string + ensure + eval("$#{stream} = #{stream.upcase}") + end + + result + end + alias :silence :capture end diff --git a/activesupport/test/core_ext/kernel_test.rb b/activesupport/test/core_ext/kernel_test.rb index 904d56a87e..ede9b0a6aa 100644 --- a/activesupport/test/core_ext/kernel_test.rb +++ b/activesupport/test/core_ext/kernel_test.rb @@ -52,6 +52,11 @@ class KernelTest < Test::Unit::TestCase class << o; @x = 1; end assert_equal 1, o.class_eval { @x } end + + def test_capture + assert_equal 'STDERR', capture(:stderr) {$stderr.print 'STDERR'} + assert_equal 'STDOUT', capture(:stdout) {print 'STDOUT'} + end end class KernelSuppressTest < Test::Unit::TestCase |