I'd like to do something like this (see below).

Is that possible?

class Tee
  @@already_redirected = false
  def self.tee(logfile, append = true)
    raise "output already redirected" if @@already_redirected
    @@already_redirected = true
    lf = File.open(logfile, append ? 'a' : 'w+')
    #TODO: store current methods
    #redefine methods
    redirect(lf)
    begin
      yield
    ensure
      lf.close
      #TODO: restore methods
    end
  end

  private
  def self.redirect(file)
    [$stdout, $stderr].each do |io|
      old_write = io.method(:write)
      class << io
        self
      end.module_eval do
        define_method(:write) do |text|
          old_write.call(text)
          file.write(text)
        end
      end
    end
  end
end

puts "start"
Tee::tee("logfile.log", true) {
  puts "Hello"
  printf "Hello again"
  system("ls -l")
}
puts "end"

-- 
Posted via http://www.ruby-forum.com/.