Skip to content

Instantly share code, notes, and snippets.

@herrphon
Created December 30, 2014 13:33
Show Gist options
  • Save herrphon/bf62bf79603ed3154494 to your computer and use it in GitHub Desktop.
Save herrphon/bf62bf79603ed3154494 to your computer and use it in GitHub Desktop.
ruby - proc, block, yield - capture stdin/out
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