Middleware
Prerequisites
An understanding of…
- The HTTP Request/Response Cycle
- MVC
How does the application know how to map HTTP requests to Controller actions?
Rack::Middleware
Rails routes are a middleware that map the HTTP Verb and Path (within a HTTP request) to a Controller action.
YourRailsApp::Application.routes.draw do
get '/profile', to: 'users#show' # UsersController.action(:show).call
end
Middleware in Use
A chain of classes that are initialized with a Rack Application, and respond to
#call
with [status_code, headers, body]
.
$ rake middleware
use Rails::Rack::Logger # responsible for the files in ./log/
use Rollbar::Middleware::Rails::RollbarMiddleware # responsible for reporting 400/500 status codes.
use ActionDispatch::Cookies
use ActionDispatch::Session::CookieStore
use ActionDispatch::Flash
...
run YourRailsApp::Application.routes # the HTTP Verbs and Paths that your app can respond to
Types of Middleware
- Development/Debugging
- Logging/Error reporting
- Session management
- Routing
Two common types: When given a HTTP request, perform a side effect, or return some information (respond).
Examples
- ActiveRecord::Migration::CheckPending
- Rack::CommonLogger
- ActionDispatch::Flash
- Fun with Rack
- Rollbar::Middleware
class Middleware
def initialize(app)
@app = app
end
def call(env)
# before HTTP response
status, headers, body = @app.call(env) # call the next middleware application
# after building HTTP response
[status, headers, body]
end
end
Questions:
- What is stored in
env
? - Where is
@app.call(env)
located in the middleware? - What happens in the
#call
method? - What does the
#call
method return? - What could we do with this?