Ruby Multiplexer - mash multiple objects together


/ Published in: Ruby
Save to your folder(s)



Copy this code and paste it in your HTML
  1. # this will relay calls to multiple objects
  2. #
  3. # objects will be removed from the multiplexer when
  4. # a call to them results in an exception
  5. #
  6. # I use it to multiplex input streams (see example below class)
  7.  
  8. class Multiplexer
  9. def initialize(*args)
  10. @streams = args
  11. end
  12.  
  13. def method_missing(m, *args)
  14. result = nil
  15.  
  16. while(t = @streams.shift)
  17. begin
  18. if(result = t.send(m,*args))
  19. @streams.push(t)
  20. return result
  21. end
  22. rescue
  23. end
  24. end
  25. end
  26. end
  27.  
  28. require 'open3'
  29.  
  30. Open3.popen3("ruby -e '$stderr.puts(\"foo\"); $stdout.puts(\"bar\"); $stderr.puts(\"baz\");'") do |input,output,error|
  31. expected = ['foo','bar','baz']
  32. input.close
  33. f=Multiplexer.new(error,output)
  34. while(line=f.gets)
  35. if((e=expected.shift) != line.chomp) then
  36. puts "ERROR: failed unit test; expected #{e}, got #{line.chomp}"
  37. end
  38. puts line
  39. end
  40. end

URL: http://www.jaredlux.com/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.