22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
# File 'lib/the_wizard_of_api.rb', line 22
def self.new(app = nil)
wizard = Rack::Builder.new do
map "/throne" do
map "/response" do
run Proc.new { |env|
client = env.fetch('faye.client')
req = Rack::Request.new(env)
client.publish('/wizard_response',req.params['response'])
[200,{},[]]
}
end
run Rack::TryStatic.new(app,{
root: Pathname.new(__FILE__).dirname.dirname.join("public").to_s,
urls: %w[/],
try: ['.html', 'index.html', '/index.html']})
end
map "/api" do
run Proc.new { |env|
body = DeferrableBody.new
client = env.fetch('faye.client')
EventMachine::next_tick {
env['async.callback'].call([200, {'Content-Type' => 'text/plain'}, body])
body.call [" " * 1024]
}
env.merge!("Body" => env["rack.input"].read)
client.publish('/api', env)
callback = env['async.callback']
client.subscribe('/wizard_response') do |message|
body.call [message]
body.succeed
end
ASYNC
}
end
run app if app
end.to_app
Faye::RackAdapter.new wizard, mount: "/faye"
end
|