Skip to content
Tutorials Center
My learning

Topics

Lesson 128 of 134 ยท Projects

Project: A Tiny Web Framework

Build a tiny web framework in Ruby: the Rack calling convention, request and response objects, a router with parameters, a middleware chain and tests that call the app directly.

Rails, Sinatra and Hanami look very different, but underneath they share one tiny idea: a web application is an object that responds to call. It receives a hash that describes the request and returns three things: a status code, a hash of headers and a body. This convention is called Rack, and it is what lets any Ruby web server run any Ruby web framework. In this project we build our own miniature framework on top of that convention: a router with URL parameters, request and response objects, a middleware chain, and a test harness that calls the application directly, with no server and no network.

If you want the big picture first, read Sinatra and Rack and Ruby on Rails Overview. Here we write the machinery ourselves, using blocks, define_method, pattern matching and Data.

The real rack gem is not available in this sandbox (require "rack" fails with a LoadError), and a real project would install it through a Gemfile. We do not need it: Rack is a convention, not a magic library, and everything below follows the same interface, so the code would run on a real server such as Puma with almost no changes.

Step 1: the Rack interface

A Rack application is anything with a call(env) method. The argument env is a hash with string keys: "REQUEST_METHOD" ("GET"), "PATH_INFO" ("/hello"), "QUERY_STRING" ("name=Ada"), "HTTP_*" entries for request headers (the header Authorization becomes "HTTP_AUTHORIZATION"), and more. The return value is an array [status, headers, body] where body is any object that responds to each and yields strings, usually an array of strings.

A lambda responds to call, so a lambda is already a complete application. To test it, we only need to build an env hash by hand.

Ruby Step 1: an app is an object that responds to call

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 first two lines show the triple returned by the application (our helper joins the body parts into one string). The class Greeter works as an application too, because it defines call; the same is true of a method object (method(:something)) or any other object. This is duck typing at its most useful: the server does not care what kind of object your application is. The helper mock_request is our stand-in for a web server. Because tests call the application directly, they are fast and need no ports.

Step 2: requests, responses and a router

Working with the raw env hash is tedious. A framework wraps it in a Request object with friendly methods, and gives handlers an easy way to build a Response. One naming trap to avoid: do not name a method method on the request class. Object#method already exists (it looks up a method object), and overriding it breaks other code that relies on it. We call it verb.

The router matches a verb and a path against a list of routes. A route like /posts/:id is compiled into a regular expression with a named capture, so /posts/42 yields {"id" => "42"}. Handlers return anything convenient (a string, a hash, a response object), and the router converts the result to a proper triple with pattern matching.

Ruby Step 2: Request, Response and Router

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.

Take the output line by line. A string from a handler becomes a text/plain response; a hash becomes JSON; nil becomes 204 No Content, and a ready-made Response is used as it is. Unknown paths give 404. A path that exists but not for this verb gives 405 Method Not Allowed with an Allow header listing the verbs that do work: PUT /users/3 finds the GET and DELETE routes for that path and says so.

Two Ruby techniques carry this code. define_method inside a loop over %w[get post put delete] generates four methods (get, post, put, delete) from one definition, instead of copying it four times. And case/in with class patterns (in Response, in String, in Hash | Array) is a readable way to convert whatever the handler returned.

The router matches [^/]+ for each parameter, so :id is a string: "42", not 42. Convert it (to_i) and decide what happens with /users/abc. A real framework does validation and conversion here, and this is also the place where URL parameters need to be treated as untrusted input.

Step 3: middleware

Often you want behavior that applies to every request: logging, authentication, error pages, headers. Copying it into every handler is repetitive and error-prone. Middleware solves it: a middleware is also a Rack application, but it holds another application and calls it. It can act before the call, after it, or instead of it.

TEXT
request  ->  Logger  ->  Rescuer  ->  Auth  ->  Router  ->  handler
response <-  Logger  <-  Rescuer  <-  Auth  <-  Router  <-  handler

The classic shape is a class whose constructor takes the next application and whose call calls it:

Ruby Step 3: middleware wraps an 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.

The builder keeps the middleware in the order they were declared and wraps them from the inside out: reverse.reduce starts with the endpoint and wraps it in the last middleware, then the one before, and so on. The first use is therefore the outermost layer, which sees the request first and the response last. The log proves it: outer: before, inner: before, then, on the way back, inner: after, outer: after. The middleware Shout upcased the body on its way out.

When a handler blows up

Without protection, an exception in a handler would travel up through the whole stack and crash the request. See what that looks like first:

Ruby An unprotected handler raises (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 first call returns [200, {}, ["Hi Ada"]]. The second ends the program with main.rb:3:in 'block in <main>': undefined method 'capitalize' for nil (NoMethodError), followed by a source excerpt (Ruby 4 adds those), because a missing parameter gave nil. In production, the server would turn this into a blank 500 page, or in the worst case leak a stack trace to the visitor. A Rescuer middleware at the top of the stack turns every unexpected exception into a controlled 500 response and records the details for the developers.

Step 4: the complete framework and application

Now everything together. The application is a miniature blog API with an in-memory store. The middleware stack has three layers:

  1. RequestLog records one line per request (GET /posts/1 -> 200) in an array. A real one would write to a file or standard output.
  2. Rescuer converts exceptions into 500 (and JSON::ParserError from a bad request body into 400).
  3. TokenAuth protects everything under /admin with a bearer token, answering 401 otherwise.

At the end, a tiny test harness exercises the app through call, with no server. It prints one line per check, so a failure is easy to spot. (In a real project you would use Minitest; we avoid it here only because its summary prints a random seed and timings.)

Ruby The complete framework, app and tests

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.

Read the test output as a specification of the framework. The bad-JSON case returns 400 because Rescuer translates JSON::ParserError before the general clause can turn it into a 500. The next test sends {}, which parses fine but makes data.fetch(:title) raise KeyError; that is a bug in the handler (it should answer 422 instead), and the harness records it as a 500. We kept it on purpose, since it shows what the safety net does, and the list of recorded errors at the end shows how a developer finds out what went wrong while the visitor saw only a neutral message. The unauthenticated admin request never reaches the router at all: TokenAuth answered with 401 and the WWW-Authenticate header that tells clients how to authenticate.

Note also that the request log lists the requests in the order of completion. RequestLog is the outermost layer, so it logs after everything below it, including the responses that Rescuer and TokenAuth produced themselves; the status code in each line is the final one the client sees.

Differences from real Rack

Our framework is a teaching model. The real thing differs in a few ways you should know:

  • env also contains rack.* keys and is mutable and shared between layers; middleware often passes information to handlers through it.
  • The body may be streamed, and bodies can have a close method that the server calls when it is finished.
  • Header names are lowercase in Rack 3, and servers add many more env keys (SERVER_NAME, HTTP_HOST, rack.url_scheme, ...).
  • Rack ships Rack::Builder, Rack::Request, Rack::Response, Rack::MockRequest and a large middleware collection. Sinatra, Roda and Rails all build on it.

Ideas to extend it

  • Add before and after hooks and a halt helper (implemented with throw/catch, see catch and throw).
  • Add a Session middleware that stores data in a signed cookie.
  • Render HTML pages with ERB templates.
  • Serve static files from a hash of path => content.
  • Implement HEAD automatically for every GET route.
  • Wrap the app in a real TCP server using TCPServer from URI and Networking Basics that parses HTTP text into an env.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a Rack application have to provide?

    Any object that responds to call and returns the status, headers and an each-able body is a Rack application, even a lambda.
  2. 2. In the stack built by use A; use B; run app, which layer sees the request first?

    The builder wraps from the inside out, so the first use becomes the outermost layer: A sees the request first and the response last.
  3. 3. Why does the framework call its request method verb instead of method?

    Naming a method after a Kernel/Object method is legal but risky. Choose a name that does not collide.
  4. 4. A request arrives for PUT /users/3 and only GET and DELETE routes exist for that path. Which response is correct?

    The resource exists but not for that verb. 405 plus an Allow header tells the client what works.
  5. 5. What is the advantage of testing an app by calling app.call(env) directly?

    Because the whole app is just an object with call, a test can pass a hand-made env and inspect the returned triple.

Summary

  • A Rack application is any object with call(env) that returns [status, headers, body]; lambdas and classes both qualify.
  • Wrap env in a Request object, build responses with a Response class, and let a router map verb and path (with :params compiled to named captures) to handlers.
  • Return 404 for unknown paths and 405 with an Allow header for a known path with the wrong verb.
  • Middleware is an app that wraps another app. A builder that wraps with reverse.reduce makes the first declared layer the outermost one.
  • Put cross-cutting concerns (logging, error handling, authentication) in middleware, with the error handler near the top so it catches everything below.
  • Because the app is just an object, tests can call it directly with a hand-made env, with no server involved.

Next: Ruby Cheat Sheet