A rack middleware is a piece of code that sits on top of your rack application. It has access to the request and other environment variables. It can do different things like return a response without going to the rack application or insert some data that will be used by the rack application.
A rack middleware is a class that needs an initialize method and a call method. The initialize method has at least one argument, the application. This application can be another middleware on the ‘chain’ or the rack application.
1 2 3 | |
The call method has one argument, the environment and should return an array with 3 elements - the status, the headers, and the body. The status should be an integer, the headers should respond to each, and the body should respond to each as well.
1 2 3 4 5 6 7 | |
In this example, the middleware will check if the request is for /rubyinfo. If it is, it will return a response. If it’s not, it will pass the request to the rack application.
To add a rack middleware, use ‘use’
1 2 | |