Class: IORedirect
Overview
IORedirect
A class to redirect $stdout, or other IO object, to a StringIO object, or any other object with a write() method.
Synopsis
s = StringIO.new
r = Redirector.redirect($stdout, s) do
$stdout.puts "this is a test"
end
Class Method Summary collapse
-
.redirect(from, to) ⇒ Object
An exception-safe class method for redirection.
Instance Method Summary collapse
-
#initialize(from, to) ⇒ IORedirect
constructor
Start redirection from one IO object to any other object with a write() method.
-
#start ⇒ Object
Start redirection, if it has not already been started.
-
#stop ⇒ Object
Stop redirection, if it is occurring.
Constructor Details
#initialize(from, to) ⇒ IORedirect
Start redirection from one IO object to any other object with a write() method. from is the IO object to redirect from, and to is the object to redirect to.
51 52 53 54 55 |
# File 'lib/more/facets/ioredirect.rb', line 51 def initialize(from, to) @from = from @to = to start() end |
Class Method Details
.redirect(from, to) ⇒ Object
An exception-safe class method for redirection
83 84 85 86 87 88 89 90 |
# File 'lib/more/facets/ioredirect.rb', line 83 def self.redirect(from, to) s = self.new(from, to) begin yield ensure s.stop end end |
Instance Method Details
#start ⇒ Object
Start redirection, if it has not already been started.
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/more/facets/ioredirect.rb', line 58 def start raise "Redirection already in progress" if @t tmp = @from.dup r, w = IO.pipe @from.reopen(w) @t = Thread.new do begin loop do s = r.read(1) # TODO: can I make this buffered? @to.write(s) end ensure @from.reopen(tmp) @t = nil end end end |
#stop ⇒ Object
Stop redirection, if it is occurring
77 78 79 80 |
# File 'lib/more/facets/ioredirect.rb', line 77 def stop raise "Redirection already stopped" if not @t @t.kill end |