Photo by Francesco Ungaro on Unsplash, Rack Lobster

Introduction

This is the first in a series of two articles. You can find the second article here or at the bottom of the page.

What is Rack?

Rack is a RubyGem that provides an interface for your Ruby web application and the application server you’re using. Rack-based applications are those that follow a set of specifications established by Rack that allow Rack to work with the application.

The Rack RubyGem serves as an interface between the application and the application server during the request-response cycle.
Rack offers support for many servers, and many applications can be Rack-based.

What makes an application Rack-based?

An application is considered Rack-based if it adheres to Rack specifications. Namely, an application must define a call method. This method is the heart of a Rack-based application. There are two requirements for the method.

A Rack app must define a method named call that takes one argument.
This constitutes a minimum viable Rack application
require 'rack'class MyApp
def call(env)
['200', { "Content-Type" => "text/plain" }, ["hello world"]]
end
end
Rack::Handler::WEBrick.run MyApp.new
require 'rack'class MyApp
def call(env)
body = "<h2>Hello in Style!</h2>"
['200', { "Content-Type" => "text/html" }, [body]]
end
end
Rack::Handler::WEBrick.run MyApp.new

What is env?

Let’s take a look at the env request hash by including it as the body of our response to the browser.

require 'rack'class MyApp
def call(env)
['200', { "Content-Type" => "text/plain" }, [env.to_s]]
end
end
Rack::Handler::WEBrick.run MyApp.new

Next level of abstraction, please

Let’s circle back to the first iteration of our simple Rack-based application.

require 'rack'class MyApp
def call(env)
['200', { "Content-Type" => "text/plain" }, ["hello world"]]
end
end
Rack::Handler::WEBrick.run MyApp.new
Rack source code here

Part 1: Summary

To summarize our discussion so far, we’ve talked about how Rack is a RubyGem that operates between a Ruby application and an application server. We’ve talked about Rack-based applications and the required call method, the env hash it takes and the 3-item Array it must return. We’ve also managed to send a response from our application to the browser.

Research analyst turned aspiring web developer. Learning the fundamentals with Launch School. Lives in Denver, CO.