t/GNUmakefile: cleanup test dependencies
[rainbows.git] / t / async_chunk_app.ru
blob007d7b28fa176691b08ecf9d6ad54ae9b8bfc7c5
1 # based on async_examples/async_app.ru by James Tucker
2 class DeferrableChunkBody
3   include EventMachine::Deferrable
5   def call(*body)
6     body.each do |chunk|
7       @body_callback.call("#{chunk.size.to_s(16)}\r\n")
8       @body_callback.call(chunk)
9       @body_callback.call("\r\n")
10     end
11   end
13   def each(&block)
14     @body_callback = block
15   end
17   def finish
18     @body_callback.call("0\r\n\r\n")
19   end
20 end if defined?(EventMachine)
22 class AsyncChunkApp
23   def call(env)
24     headers = {
25       'Content-Type' => 'text/plain',
26       'Transfer-Encoding' => 'chunked',
27     }
28     delay = env["HTTP_X_DELAY"].to_i
30     case env["rainbows.model"]
31     when :EventMachine, :NeverBlock
32       body = DeferrableChunkBody.new
33       body.callback { body.finish }
34       task = lambda {
35         env['async.callback'].call([ 200, headers, body ])
36         EM.add_timer(1) {
37           body.call "Hello "
39           EM.add_timer(1) {
40             body.call "World #{env['PATH_INFO']}\n"
41             body.succeed
42           }
43         }
44       }
45       delay == 0 ? EM.next_tick(&task) : EM.add_timer(delay, &task)
46     when :Coolio
47       # Cool.io only does one-shot responses due to the lack of the
48       # equivalent of EM::Deferrables
49       body = [ "Hello ", "World #{env['PATH_INFO']}\n", '' ].map do |chunk|
50         "#{chunk.size.to_s(16)}\r\n#{chunk}\r\n"
51       end
53       next_tick = Coolio::TimerWatcher.new(delay, false)
54       next_tick.on_timer { env['async.callback'].call([ 200, headers, body ]) }
55       next_tick.attach(Coolio::Loop.default)
56     else
57       raise "Not supported: #{env['rainbows.model']}"
58     end
59     nil
60   end
61 end
62 run AsyncChunkApp.new