Skip to content

Instantly share code, notes, and snippets.

@ozydingo
Created June 9, 2016 08:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ozydingo/1bd14ef6d4bdee85444ccacc9a887603 to your computer and use it in GitHub Desktop.
Save ozydingo/1bd14ef6d4bdee85444ccacc9a887603 to your computer and use it in GitHub Desktop.
Ruby class for capturing puts / stdout buffer
require 'stringio'
class CaptureStdout
def initialize(&blk)
@handler = blk
end
def capture
StringIO.open do |io|
stash = $stdout
$stdout = io
yield
$stdout = stash
handle_output(io)
end
end
def handle_output(io)
@handler.call(io.string)
end
end
# define your capturer and its behavior
c = CaptureStdout.new{|s| s.each_line{|l| puts "Received: " + l.upcase}}
# caputre!
c.capture{ puts "hello"; puts "world" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment