Skip to content

Instantly share code, notes, and snippets.

@ozydingo
Last active June 9, 2016 08:37
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/9365636124b923f0f816ae833640c713 to your computer and use it in GitHub Desktop.
Save ozydingo/9365636124b923f0f816ae833640c713 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 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