class Rack::Events

This middleware provides hooks to certain places in the request /

response lifecycle. This is so that middleware that don't need to filter the response data can safely leave it alone and not have to send messages down the traditional “rack stack”.

The events are:

## Order

`on_start` is called on the handlers in the order that they were passed to the constructor. `on_commit`, on_send`, `on_finish`, and `on_error` are called in the reverse order. `on_finish` handlers are called inside an `ensure` block, so they are guaranteed to be called even if something raises an exception. If something raises an exception in a `on_finish` method, then nothing is guaranteed.

Public Class Methods

new(app, handlers) click to toggle source
# File lib/rack/events.rb, line 101
def initialize(app, handlers)
  @app      = app
  @handlers = handlers
end

Public Instance Methods

call(env) click to toggle source
# File lib/rack/events.rb, line 106
def call(env)
  request = make_request env
  on_start request, nil

  begin
    status, headers, body = @app.call request.env
    response = make_response status, headers, body
    on_commit request, response
  rescue StandardError => e
    on_error request, response, e
    on_finish request, response
    raise
  end

  body = EventedBodyProxy.new(body, request, response, @handlers) do
    on_finish request, response
  end
  [response.status, response.headers, body]
end

Private Instance Methods

make_request(env) click to toggle source
# File lib/rack/events.rb, line 144
def make_request(env)
  Rack::Request.new env
end
make_response(status, headers, body) click to toggle source
# File lib/rack/events.rb, line 148
def make_response(status, headers, body)
  BufferedResponse.new status, headers, body
end
on_commit(request, response) click to toggle source
# File lib/rack/events.rb, line 132
def on_commit(request, response)
  @handlers.reverse_each { |handler| handler.on_commit request, response }
end
on_error(request, response, e) click to toggle source
# File lib/rack/events.rb, line 128
def on_error(request, response, e)
  @handlers.reverse_each { |handler| handler.on_error request, response, e }
end
on_finish(request, response) click to toggle source
# File lib/rack/events.rb, line 140
def on_finish(request, response)
  @handlers.reverse_each { |handler| handler.on_finish request, response }
end
on_start(request, response) click to toggle source
# File lib/rack/events.rb, line 136
def on_start(request, response)
  @handlers.each { |handler| handler.on_start request, nil }
end