Created
November 6, 2014 16:18
-
-
Save porras/75926319d9e157fd4000 to your computer and use it in GitHub Desktop.
Wrapping an object that reads in a wrapper you can write to
This file contains hidden or 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
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