DEV Community

Cover image for 49 Days of Ruby: Day 38 - Rack
Ben Greenberg
Ben Greenberg

Posted on

49 Days of Ruby: Day 38 - Rack

Welcome to day 38 of the 49 Days of Ruby! 🎉

Now that we have looked at building API calls, and using SDKs, it is time to explore Rack!

What is Rack? From the README:

Rack provides a minimal, modular, and adaptable interface for developing web applications in Ruby. By wrapping HTTP requests and responses in the simplest way possible, it unifies and distills the API for web servers, web frameworks, and software in between (the so-called middleware) into a single method call.

In a couple of short days, we will start looking at web frameworks, and no matter how impressive they appear, they owe their existence to Rack.

Rack defines the underlying architecture for how our code interacts with the web. That code can be a couple lines or an entire web framework, like Ruby on Rails!

Let's take a look at an example:

class WebApp
  def call(env)
    status  = 200
    headers = { "Content-Type" => "text/plan" }
    body    = ["My first web app, wow!"]

    [status, headers, body]

Enter fullscreen mode Exit fullscreen mode

The #call method is a necessary component of the Rack architecture. Inside, the #call method, we can provide various criteria that define what happens when a browser or other web client reaches it.

In this case, we want to return a HTTP status of 200, which means, OK, or in general terms, this works! Then, we return some web headers, namely, saying the content will be plain text. Lastly, we define the body, which is the content.

The run keyword is another part of the Rack flow.

Rack has a helper utility called rackup that you can run from your console. With the code above saved in a file called app.rb, run rackup app.rb from your console.

You should see something like this:

$ INFO  WEBrick::HTTPServer#start: pid=00000 port=9292
Enter fullscreen mode Exit fullscreen mode

Now, in your browser, go to http://localhost:9292. What do you see?

That's right, you just created your first web application. Congrats!

That's it for today. Tomorrow, we'll explore the power of middleware using Rack.

Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.

Top comments (0)