| Class | IORedirect |
| In: |
lib/more/facets/ioredirect.rb
|
| Parent: | Object |
A class to redirect $stdout, or other IO object, to a StringIO object, or any other object with a write() method.
s = StringIO.new
r = Redirector.redirect($stdout, s) do
$stdout.puts "this is a test"
end
An exception-safe class method for redirection
# File lib/more/facets/ioredirect.rb, line 80
80: def self.redirect(from, to)
81: s = self.new(from, to)
82: begin
83: yield
84: ensure
85: s.stop
86: end
87: end
Start redirection, if it has not already been started.
# File lib/more/facets/ioredirect.rb, line 55
55: def start
56: raise "Redirection already in progress" if @t
57: tmp = @from.dup
58: r, w = IO.pipe
59: @from.reopen(w)
60: @t = Thread.new do
61: begin
62: loop do
63: s = r.read(1) # TODO: can I make this buffered?
64: @to.write(s)
65: end
66: ensure
67: @from.reopen(tmp)
68: @t = nil
69: end
70: end
71: end