Class: IO::Redirect

Inherits:
Object show all
Defined in:
lib/carat/io-redirect.rb

Overview

IO::Redirect

A class to redirect $stdout, or other IO object, to a StringIO object,
or any other object with a write() method.

== Synopsis

  require 'raspberry/new/io-redirect'

  s = StringIO.new
  r = Redirector.redirect($stdout, s) do
    $stdout.puts "this is a test"
  end

== Legal

Ported from Ruby treasures
Copyright (C) 2002 Paul Brannan <[email protected]>

You may distribute this software under the same terms as Ruby (see the file
COPYING that was distributed with this library).

== Version

  $id: io-redirect.rb 2004/10/27 10:00:01 transami Exp $

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(from, to) ⇒ Redirect

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.



36
37
38
39
40
# File 'lib/carat/io-redirect.rb', line 36

def initialize(from, to)
  @from = from
  @to = to
  start()
end

Class Method Details

.redirect(from, to) ⇒ Object

An exception-safe class method for redirection



68
69
70
71
72
73
74
75
# File 'lib/carat/io-redirect.rb', line 68

def self.redirect(from, to)
  s = self.new(from, to)
  begin
    yield
  ensure
    s.stop
  end
end

Instance Method Details

#startObject

Start redirection, if it has not already been started.



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/carat/io-redirect.rb', line 43

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

#stopObject

Stop redirection, if it is occurring



62
63
64
65
# File 'lib/carat/io-redirect.rb', line 62

def stop
  raise "Redirection already stopped" if not @t
  @t.kill
end