Skip to content
Tutorials Center
My learning

Topics

Lesson 114 of 134 ยท Web and Ecosystem

Sinatra and Rack

Learn how Ruby web apps work. Build a Rack-style app by hand, call it with a plain hash, add middleware, write a tiny Sinatra-style DSL, and read real Sinatra code.

Every Ruby web framework, from Rails to Sinatra to Hanami, sits on top of one tiny idea called Rack. Rack is not a program you run; it is an agreement about how a web server and your Ruby code talk to each other. Once you understand that agreement, frameworks stop being magic: they are just convenient ways to build objects that follow it.

Our runner has no network and no third-party gems, so rack and sinatra are not installed here. That is fine. The Rack agreement is so small that we can follow it with plain Ruby, call our apps directly with a hash instead of a real HTTP request, and see every byte of the response. Anything that needs a real gem is labelled as a read-only example.

The Rack agreement

A Rack application is any Ruby object that responds to call. The server calls it with one argument, the environment (a hash describing the request), and expects back an array of exactly three things:

  1. the status code, an Integer such as 200;
  2. the headers, a Hash of strings;
  3. the body, an object that responds to each and yields strings (usually an array of strings).

A lambda already responds to call, so the smallest web app in Ruby is a lambda. In a real project you would put it in config.ru and start a server such as Puma. Here we simply call it ourselves.

Ruby The smallest Rack-style app

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

That is the whole contract. A real server (Puma, Falcon, Unicorn) parses the incoming HTTP text, builds the env hash, calls your app, and writes the three parts back to the socket as an HTTP response. Your code never touches sockets.

Rack 3 requires header names to be lowercase strings ("content-type"). Older code and tutorials use "Content-Type". Servers accept both, but lowercase is the modern style, and it is what we use here.

What is in the environment hash

The env hash is CGI-style: keys are uppercase strings. The ones you meet most often are REQUEST_METHOD ("GET", "POST"), PATH_INFO (the path after the app's mount point), QUERY_STRING (everything after the ?), and rack.input (an IO-like object holding the request body). HTTP request headers appear as HTTP_ plus the uppercased name, so Accept-Language becomes HTTP_ACCEPT_LANGUAGE.

To test our apps without a server, we need a way to build such a hash. A small helper does it, using StringIO for the body (see StringIO and Streams).

Ruby Building a request by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

URI.decode_www_form turns a query string or a form body into pairs. Notice that every value is a string: "false" is not false. Parsing and converting types is the framework's job, and it is the first place bugs hide.

An app with several routes

One lambda is not enough for a site. A real app looks at REQUEST_METHOD and PATH_INFO, picks a handler, and returns the right triple. We can write that with a case and pattern matching. Because an app is "anything with call", a class with a call method works just as well, and it can keep state between requests.

Ruby A routing app as a class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Study how the status codes tell the story. 201 means "created", 422 means "I understood you but the content is invalid", 405 means "that path exists, but not for that method", and 404 means there is no such path. Choosing the right code is part of designing a web API.

Middleware: apps that wrap apps

Because an app is just an object with call, you can write an object that holds another app, does something before and after calling it, and has call itself. That is middleware. The classic uses are logging, authentication, compression, caching, and catching errors. Middleware can be stacked like onions: the request travels inward through each layer, and the response travels back outward.

Ruby Two middleware layers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The request /boom raises inside core. ErrorCatcher is the closest layer, so it turns the exception into a 500 response, and the outer layers never notice anything went wrong; they still log and add their header. Order matters: if you moved ErrorCatcher to the outside, the logger would see the exception instead.

Building the stack by hand with nested new calls gets unwieldy, so real Rack gives you a builder. In config.ru:

Ruby
# read-only example: a config.ru file (needs the rack gem and a server)
require_relative "app"

use Rack::Deflater              # compress responses
use Rack::Runtime               # add an X-Runtime header
map("/admin") { run AdminApp.new }
run NotesApp.new

use stacks a middleware, map mounts an app under a path prefix, and run names the final app. You start it with rackup or bundle exec puma. The rack gem also provides Rack::Request and Rack::Response, friendly wrappers around the env hash and the triple. We will write simple stand-ins for those in Project: A Tiny Web Framework.

What happens when you require rack here

Rack is a gem, not part of Ruby, so on this runner it is simply missing. This is exactly the error you would see on your own machine before running bundle install:

Ruby Requiring a gem that is not installed (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The runner prints main.rb:1:in 'Kernel#require': cannot load such file -- rack (LoadError). The fix on a real machine is a line gem "rack" in the Gemfile and bundle install; see RubyGems and Bundler. Notice the lesson of the section: this lesson needs no gem to understand Rack.

Sinatra: a DSL on top of Rack

Sinatra is the best-known small framework. It turns the routing case we wrote into a readable DSL: you write the HTTP verb, the path, and a block. A complete app is a handful of lines. This is a read-only example, because it needs the sinatra gem and a real server:

Ruby
# read-only example: needs the sinatra gem
require "sinatra"

get "/" do
  "Hello, world"
end

get "/hello/:name" do
  "Hello, #{params[:name]}"
end

post "/notes" do
  status 201
  content_type :json
  { id: 1, text: params[:text] }.to_json
end

Run the file with ruby app.rb and Sinatra starts a server on port 4567. The last expression of each block becomes the body; status and content_type adjust the rest of the triple; params merges path captures, the query string and the form body.

How does get "/" do ... end work with no object in sight? Sinatra defines get, post and friends as methods on main and delegates them to an application class. Each call stores the block and a compiled path pattern in a routing table. When a request comes in, Sinatra's call(env) (it is a Rack app!) finds the first matching route, runs the block with instance_eval so that params and status are available, and builds the triple. You can write a miniature of this in under forty lines.

Ruby A mini Sinatra built from scratch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The pieces are all things you already know. define_singleton_method creates the class-level get/post/delete macros (define_method and dynamic methods). Each route stores a block, and instance_eval runs that block with self set to the app, so the block can call params and status as if they were its own methods (instance_eval and class_eval). The route table lives in a class instance variable, and subclasses get their own.

Sinatra, Rack and Rails

Rails is a Rack application too: Rails.application.call(env) returns the same triple, and its middleware stack (bin/rails middleware) is a list of Rack middleware, including session handling, parameter parsing and exception pages. Sinatra, Hanami, Roda and Cuba all do likewise. That shared interface is why you can swap servers (Puma, Falcon, Unicorn) or add middleware from one framework to another.

Choosing between them:

  • Sinatra or Roda for small services, webhooks and prototypes where you want to see every moving part.
  • Rails when you need a database layer, background jobs, mailers, an asset pipeline and conventions for a team (Ruby on Rails Overview).
  • Plain Rack when you want a tiny, dependency-free endpoint, a health check, or a middleware.

Pitfalls professionals know

  • Bodies must respond to each. Returning a bare string instead of ["text"] fails in the server, not in your tests. Always return an array (or an enumerable).
  • Mutating a shared env is allowed and common (middleware stores things under custom keys such as "myapp.user"), but namespace your keys so you never collide with another layer.
  • State in the app object is shared between requests, and servers like Puma run requests on several threads. The @notes array in our example is not thread-safe; real apps keep state in a database or protect it with a Mutex (Mutex, Queue and ConditionVariable).
  • Reading rack.input twice returns nothing the second time unless you rewind it. Middleware that reads the body must rewind afterwards.
  • Do not trust parameters. They are always strings from the outside world; validate and convert them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What must an object do to be a Rack application?

    Rack is only a calling convention. Anything with call(env) that returns a three-element array is an app, so lambdas and plain classes both work.
  2. 2. What does a body in the Rack triple need to respond to?

    The server iterates over the body with each and writes every yielded string to the client, which is why a bare string is not a valid body.
  3. 3. In which order do the layers see a request when you write RequestLogger.new(PoweredBy.new(core))?

    The outermost middleware gets the request first and the response last, like layers of an onion.
  4. 4. What status code fits a POST with a blank note that the server understood but rejects?

    422 (Unprocessable Content) says the request was well formed but the data is invalid. 404 means no such path and 405 means the method is not allowed.
  5. 5. Why does Sinatra's get block have access to params and status?

    Sinatra evaluates the stored block in the context of an app instance, so self is the app and its methods are available.

Summary

  • A Rack app is any object with call(env) that returns [status, headers, body]; the body responds to each.
  • The env hash is CGI-style (REQUEST_METHOD, PATH_INFO, QUERY_STRING, rack.input), so you can test apps by calling them with a hand-built hash.
  • Middleware wraps an app in an object with the same call interface, which enables logging, error pages and header changes in layers.
  • rack and sinatra are gems that are not installed on this runner; a missing gem raises LoadError.
  • Sinatra is a routing DSL over Rack, built from define_singleton_method and instance_eval; Rails and others use the same interface.
  • Shared mutable state in an app object is dangerous with multi-threaded servers.

Next: Database Access Ideas