Created
June 9, 2016 08:21
-
-
Save ozydingo/1bd14ef6d4bdee85444ccacc9a887603 to your computer and use it in GitHub Desktop.
Ruby class for capturing puts / stdout buffer
This file contains 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' | |
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