This content has been automatically translated from Ukrainian.
Middleware in Ruby on Rails, it is an intermediate layer between the client request and the web application. It receives a request before it enters the controller and can modify or process it. Likewise, Middleware can intercept a response from an application before it is sent to a client.
Rails is built on top of the Rack library, which defines the standard for such intermediate layers. Middleware in this context is a regular Ruby class that implements the call (env) method. The env option contains all information about the HTTP request (eg path, headers, method). The method must return an array of three elements: response status, headers, and body.
The simplest example of your own Middleware can look like this:
class RequestLogger
def initialize(app)
@app = app
end
def call(env)
puts "Retrieved query to #{env['PATH_INFO']}"
status, heads, body = @app.call(env)
puts "Returned #{status} status"
[status, heads, body]
end
end
In this example, each request will be logged into the console - both upon arrival and after processing.
Middleware is often used for the following tasks:
- login of requests and responses;
- caching;
- error handling;
- token authentication or verification;
- compression or modification of the response body;
- establishing common headings.
In Rails, the middleware chain is defined in the config/application.rb file or viewed by the command:
bin/rails middleware
To add your own middleware, you can paste it into the stack:
config.middleware.use RequestLogger
or between other layers:
config.middleware.insert_before Rack::Runtime, RequestLogger
Middleware helps isolate the technical aspects of query handling - logic is not directly related to business code. This makes the application cleaner, more extensible and easier to maintain.
This post doesn't have any additions from the author yet.