Class IORedirect
In: lib/more/facets/ioredirect.rb
Parent: Object

IORedirect

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

Methods

new   redirect   start   stop  

Public Class methods

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.

[Source]

    # File lib/more/facets/ioredirect.rb, line 48
48:   def initialize(from, to)
49:     @from = from
50:     @to = to
51:     start()
52:   end

An exception-safe class method for redirection

[Source]

    # 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

Public Instance methods

Start redirection, if it has not already been started.

[Source]

    # 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

Stop redirection, if it is occurring

[Source]

    # File lib/more/facets/ioredirect.rb, line 74
74:   def stop
75:     raise "Redirection already stopped" if not @t
76:     @t.kill
77:   end

[Validate]