Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 21st, 2012  |  syntax: None  |  size: 0.68 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. require 'stringio'
  2.  
  3. old_out = $stdout
  4.  
  5. class TeeIO < StringIO
  6.   def initialize(stdout)
  7.     super()
  8.     @stdout = stdout
  9.   end
  10.  
  11.   def write(*args)
  12.     super
  13.     @stdout.write(*args)
  14.   end
  15. end
  16.  
  17. class ProxyIO < BasicObject
  18.   def initialize(*streams)
  19.     @streams = streams
  20.   end
  21.  
  22.   private
  23.  
  24.   def method_missing(name, *args, &block)
  25.     result = nil
  26.     @streams.each do |stream|
  27.       result = stream.send(name, *args, &block)
  28.     end
  29.     result
  30.   end
  31. end
  32.  
  33. $stdout = tee = TeeIO.new(old_out)
  34. puts "hello world!"
  35. $stdout = old_out
  36. puts "From tee:"
  37. puts tee.string
  38.  
  39. $stdout = ProxyIO.new(old_out, stringio = StringIO.new)
  40. puts "hello again!"
  41. $stdout = old_out
  42. puts "From proxy:"
  43. puts stringio.string