Rack in Ruby: Cool beans

Michael Corrieri
3 min readMay 11, 2021

So what is rack?

Rack is a minimal interface that allows us to develop web applications in Ruby. Rack wraps HTTP requests and responses in Ruby objects. It allows us to connect a variety of application servers to frameworks. Basically…rack is the meat in the sandwich, the layer between our framework and our application server.

Photo by Seriously Low Carb on Unsplash

A rack application:

  • is a Ruby object which responds to call
  • Accepts one parameter: env
  • Returns an array with exactly 3 elements

1. Status code (integer)

2. Headers (hash)

3. Body (enumerable)

[Status, { Headers }, [Body] ]

So below we have an example of the most basic rack application(with a dope class name). But why use rack? What makes it cool?

Rack is great because it’s so simple. It can also be customized based on our applications. Not only that, but rack comes with a lot of useful middleware:

  • Rack::ContentType — allows us to set a default Content-Type header for responses from the server
  • Rack::Lint —checks to make sure our Rack app conforms to Rack specs
  • Rack::Reloader — reloads files automatically, useful when modifying files

What is middleware exactly?

Rack middleware is an important part of the request/response relationship. Just like the sandwich above, middleware is a layer between the user and our app. Think of middleware as a way to help execute our tasks properly. Middleware allows us to intercept/change requests. It is also useful for logging and parsing through our request object.

And how can we run our sweet code with rack? Simply type $ rackup “whateveryourfilenameis”.ru. In the terminal we will see something like this printed:

For our very basic blog example, the only part we will care about is the final part stating “port=9292”. This tells us that if we enter “localhost:9292” into our URL and hit enter, we will get to finally view our beautiful content (body) from our above code.

Last useful tip: Tired of making edits to your code and having to manually shut down and restart the server each time?

use Rack::Reloader (the middleware we talked about above) is a very useful tool. It has one parameter when it is instantiated, which if we set to 5, will reload our code every 5 seconds.

--

--

Michael Corrieri

Software Engineering student at Flatiron School. Environmental & Occupational Health Sciences MPH. Based in Brooklyn, NY