Created
December 30, 2014 13:33
-
-
Save herrphon/bf62bf79603ed3154494 to your computer and use it in GitHub Desktop.
ruby - proc, block, yield - capture stdin/out
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'stringio' | |
require 'pp' | |
def capture_all(proc) | |
begin | |
$stdout = StringIO.new | |
$stderr = StringIO.new | |
proc.call | |
yield | |
result = {} | |
result[:stdout] = $stdout.string | |
result[:stderr] = $stderr.string | |
ensure | |
$stdout = STDOUT | |
$stderr = STDERR | |
end | |
result | |
end | |
def capture_output(proc, &block) | |
error = nil | |
result = capture_all(proc) do | |
puts 'haha this comes in the end' | |
end | |
yield result[:stdout] , result[:stderr] if block_given? | |
result | |
end | |
def invoke_something() | |
output = capture_output( proc { puts 'hello test'; $stderr.puts 'error error error' }) do |out, err| | |
puts 'testing ....' | |
puts out | |
puts err | |
end | |
return output | |
end | |
pp invoke_something |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment