Skip to content

Instantly share code, notes, and snippets.

@porras
Created November 6, 2014 16:18
Show Gist options
  • Save porras/75926319d9e157fd4000 to your computer and use it in GitHub Desktop.
Save porras/75926319d9e157fd4000 to your computer and use it in GitHub Desktop.
Wrapping an object that reads in a wrapper you can write to
class ObjectThatInsistsOnCallingRead
def initialize(io)
while s = io.read(10)
print s
end
end
end
class WrapperToWhichYouCanWrite
def initialize
@read_io, @write_io = IO.pipe
@thread = Thread.new do
ObjectThatInsistsOnCallingRead.new(@read_io)
end
end
def write(s)
@write_io.write(s)
end
def close
@write_io.close.tap do
@thread.join
end
end
end
# using original API
require 'stringio'
io = StringIO.new('bla bla bla')
o = ObjectThatInsistsOnCallingRead.new(io)
# using "push IO"
w = WrapperToWhichYouCanWrite.new
10.times do |i|
w.write(i.to_s)
end
w.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment