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

Untitled

By: a guest on Jun 4th, 2012  |  syntax: None  |  size: 0.68 KB  |  hits: 11  |  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 "eventmachine"
  2.  
  3. class DeferrableBody
  4.   include EventMachine::Deferrable
  5.  
  6.   def call(body)
  7.     body.each do |chunk|
  8.       @body_callback.call(chunk)
  9.     end
  10.   end
  11.  
  12.   def each &blk
  13.     @body_callback = blk
  14.   end
  15. end
  16.  
  17. class AsyncApp
  18.   def call(env)
  19.     body = DeferrableBody.new
  20.  
  21.     EventMachine::next_tick {
  22.       env['async.callback'].call [200, {'Content-Type' => 'text/plain'}, body]
  23.       body.call ["Hey!\n"]
  24.     }
  25.  
  26.     EventMachine::add_timer(2) {
  27.       body.call ["Woah, async!\n"]
  28.  
  29.       EventMachine::add_timer(3) {
  30.         body.call ["Cheers then!"]
  31.         body.succeed
  32.       }
  33.     }
  34.  
  35.     throw :async # Still works for supporting non-async frameworks...
  36.   end
  37.  
  38. end
  39.  
  40. run AsyncApp.new