Class: Rack::Async2Sync

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/async2sync.rb

Overview

A Rack middleware that transforms async requests (using thin + async_sinatra for example) into synchronous requests Useful for testing with a minimum of changes in your testing environment. e.g.

require 'sinatra/base'
require 'sinatra/async'
require 'rack/async2sync'
require 'spec'
require 'rack/test'
Test::Unit::TestCase.send :include, Rack::Test::Methods

class MyAsyncRackApp < Sinatra::Base
  register Sinatra::Async
  aget '/delay/:n' do |n|
    EM.add_timer(n.to_i) { body { "delayed for #{n} seconds" } }
  end
end

def app
  Rack::Async2Sync.new(MyAsyncRackApp)
end

it "requests the /delay/:n asynchronous method" do
  get '/delay/2'
  # you can use the usual methods of Rack::Test::Methods
  last_response.status.should == 200
  last_response.body.should == "delayed for 2 seconds"
end

Author: Cyril Rohr ([email protected])

Defined Under Namespace

Classes: AsyncResponse

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Async2Sync

Returns a new instance of Async2Sync.



43
44
45
# File 'lib/rack/async2sync.rb', line 43

def initialize(app, options = {})
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



47
48
49
50
51
52
53
54
55
# File 'lib/rack/async2sync.rb', line 47

def call(env)
  response = AsyncResponse.new
  EM.run do      
    catch(:async) do
      @app.call(env.merge('async.callback' => response))
    end
  end  
  [response.status, response.headers, response.body]
end