Last active
June 9, 2016 08:37
-
-
Save ozydingo/9365636124b923f0f816ae833640c713 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 do | |
puts "hello" | |
puts "world" | |
end | |
# --- output: --- | |
# Received: HELLO | |
# Received: WORLD |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment