Ruby, Tech

Rack Sailing

In this article we will discuss how we can sail with Rack in a real-world problem.

What Is Rack

Rack is a minimalistic Ruby Web server Interface. As a matter of fact, we can use Rack to build web applications if we follow its protocol. Notably, the protocol is straightforward. We need a Ruby object that responds to the call method which returns a three-element Array:

To try the above rack application:

Write the rack_hello_world.rb file and execute:

The Middleware

We can compose Rack applications together using middlewares. A middleware basically lets us wrap different inputs and outputs in order to integrate them into our problem-solving.

One common usage is in Rails. For example, Rails uses middlewares to wrap HTTP requests in a simple way.

Continuing from the previous example lets implement a middleware which will add some headers to our response:

The response headers:

The Real World

For a real-world usage of a Rack middleware, we can open the Rails project.

As a matter of fact, we can observe that the tap is being used. This basically enables us to manipulate the app object(here the response) in a clean way at a later time. To put it differently, the logic is that will have to return before the tap block gets executed.

The above is equivalent to:

It’s important to realize that if we want to place a middleware before the ActionDispatch::SSL one we would have to tap(sic) into the object after the ActionDispatch::SSL middleware is done.

Indeed, we can observe this functionality if we extend our previous example:

Notice how EditSomeHeaders is being placed before AddSomeHeaders in the middleware stack.

To clarify, execute:

Meanwhile, the full code example is available on github.


In this article, we’ve explored the basic concepts of Rack, built a Rack middleware and investigated how Rails utilizes
Rack to enforce the SSL policy.

All things considered, reading the code under the hood of a famous or well-engineered library or framework can teach us new methodologies and ways of solving problems. In essence, going through the Rails source code taught us how to use the tap method to manipulate a Rack object that is being manipulated later in the stack.