# Build Your Own Router in Ruby

*Published on March 31, 2024*

---


This is the second bonus post in my course&nbsp;Rails Companion: build a web application in Ruby without Rails. Today, we'll learn how routing works in its essence and build our own router from scratch, without using any third-party gems. We'll use some metaprogramming, but I promise it's nothing complicated.

Our router will look somewhat similar to Rails. It will accept a URI and a block, providing a very simple and expressive method to define routes and behavior without complicated routing configuration.

```ruby
Router.draw do
  get('/') { 'Hello world' }
end
```

The only difference is this: instead of directing to a resource, or a&nbsp;`controller#action`&nbsp;like Rails router, our router returns a plain string response, just like&nbsp;[Sinatra](https://sinatrarb.com/intro.html).

**By the way, if you haven't read them already, check out the course announcement and the first bonus article in the course:**

- Rails Companion: Build a Web App in Ruby Without Rails
- [Let’s Build a Web Application in Ruby without Rails](/building-web-application-without-rails)

In future articles in the series, we'll implement our own controllers and models, process forms and query data, connect to the database, write our own authentication, and much more.&nbsp;**All in plain Ruby, too!**&nbsp;If that sounds interesting, consider&nbsp;enrolling in the course.

Finally, if you don't want to read the full article (\>2000 words) and just want to see the final code, check out the&nbsp;[GitHub repository](https://github.com/akshayKhot/weby/tree/rails-router)&nbsp;and switch to the&nbsp;`rails-router`&nbsp;branch.

Alright, let's start by understanding what a router is and what it does, in the context of a web application.

* * *

## What is a Router?

A router is that part of the web application that determines where the incoming request should go. It figures it out by examining the request URL and then invoking a pre-defined function (or a handler) for that path. Internally, it stores the mapping between the URL patterns and the corresponding handlers.

In Ruby on Rails, the router sends the incoming request to an action method on a controller.

![router.png](https://writesoftwarewell.com/media/yldhq2d8p51lg24s3wc71tkom70p.png "Rails Router")

💡In the next post, we'll build our own controllers and modify our router (that we'll build today) to dispatch the request to the&nbsp;`controller#action`&nbsp;code.

To learn more about the Rails Router in-depth, please read the following post: [Understanding the Rails Router: Why, What, and How](/understanding-rails-router-why-what-how)

In fact, it would be better if you first read the above article and then come back to this one. That will give you a much better context to understand this post. Don't sweat it, though! I assume no prior knowledge of routing to understand this post.

### Current Setup

If you've read&nbsp;[the first article in the series](/building-web-application-without-rails), you should have the following script, which is a barebone, simple-yet-complete web application.

```ruby
# # weby/app.rb

class App
  def call(env)
    # a hash containing response headers
    headers = {
      "Content-Type" => "text/html"
    }

    # an array containing the HTML response string
    response = ["<h1>Hello World</h1>"]

    # an array containing
    # 1. HTTP status code
    # 2. HTTP headers 
    # 3. HTTP response
    [200, headers, response]
  end
end
```

Right now, our application does only one thing. Whenever a request arrives, it returns the response&nbsp;**`Hello World!`**&nbsp;to the browser. It sends the same response, regardless of the request URL.

```bash
➜ curl localhost:9292
<h1>Hello World</h1>

➜ curl localhost:9292/posts
<h1>Hello World</h1>

➜ curl localhost:9292/posts/new
<h1>Hello World</h1>
```

Having a web application that returns the same response for every request isn't very exciting... or useful! Let's make it smart by returning a different response based on the incoming HTTP request's path.

**To keep things simple, I'll make the following assumptions:**

- Our application only supports HTTP GET requests,
- It only needs to handle the following three routes.

<table><tbody><tr><th class="lexxy-content__table-cell--header"><p><b><strong>URL Pattern</strong></b></p></th><th class="lexxy-content__table-cell--header"><p><b><strong>Action</strong></b></p></th></tr><tr><td><p>/</p></td><td><p>shows the home page</p></td></tr><tr><td><p>/articles</p></td><td><p>shows all articles</p></td></tr><tr><td><p>/articles/1</p></td><td><p>shows a single article</p></td></tr><tr><td><p>/random</p></td><td><p>"no route found"</p></td></tr></tbody></table>

- For all other URLs, it returns&nbsp;`no route found`&nbsp;message.

Let's get to it.

## The Router Class

Let's create a new&nbsp;`Router`&nbsp;class in the current directory as follows. It maintains a&nbsp;`@routes`&nbsp;Hash as the internal data structure to store the URL patterns along with their corresponding handlers.

```ruby
# weby/router.rb

class Router
  def initialize
    @routes = {}
  end

  def get(path, &blk)
    @routes[path] = blk
  end

  def build_response(path)
    handler = @routes[path] || -> { "no route found for #{path}" } 
    handler.call 
  end
end
```

💡 A handler is simply a Ruby block that will be called when our app receives a request to the corresponding path.

If you're not that familiar with blocks and lambdas in Ruby, this code might not make much sense. I recommend you read the following post for a deeper understanding of blocks, procs, and lambdas:

[Blocks, Procs, and Lambdas: A Beginner’s Guide to Closures and Anonymous Functions in Ruby](/ruby-block-proc-lambda-and-differences-between-them)

The&nbsp;`get`&nbsp;method takes a URL path and a block as arguments. The block represents the handler code that should be executed when a request matching that path arrives. It then stores the path along with the handler in the&nbsp;`@routes`&nbsp;hash.

```ruby
def get(path, &blk)
  @routes[path] = blk
end
```

Finally, the&nbsp;`build_response`&nbsp;method takes the path of the current request. It finds the corresponding handler from the&nbsp;`@routes`&nbsp;mapping. If the path is not stored in the mapping, we set the handler to a default lambda that returns the message&nbsp;`no route found`.

```ruby
def build_response(path)
  handler = @routes[path] || -> { "no route found for #{path}" } 
  handler.call 
end
```

Once we find the handler block for the current path, we&nbsp;`call`&nbsp;it and return the generated output back to the application.

## Using the Router

Let's put the&nbsp;`Router`&nbsp;class to good use.

First, we define the routes that our application needs, and then we use the&nbsp;`build_response`&nbsp;method on the router to generate the HTTP response.

```ruby
# weby/app.rb

require_relative './router'

class App
  attr_reader :router

  def initialize
    @router = Router.new

    router.get('/') { "Akshay's Blog" }
    
    router.get('/articles') { 'All Articles' }
    
    router.get('/articles/1') { "First Article" }
  end

  def call(env)
    headers = { 'Content-Type' => 'text/html' }
    
    response_html = router.build_response(env['PATH_INFO'])
    
    [200, headers, [response_html]]
  end
end
```

Note that we're setting up the router and initializing the routes in the constructor, and not in the&nbsp;`call`&nbsp;method. This is important. The constructor is called at the beginning when the application boots up, and is never executed again. In contrast, the&nbsp;`call`&nbsp;method is invoked every time a new request comes in.

💡 **We want to initialize the router only once, at the beginning.**

And we're done. Restart the application, and be prepared to be amazed.

![articles-route.png](https://writesoftwarewell.com/media/2qf8bimufrk0tqu4pivangbqbs09.png "Articles Route")

Other routes work as expected, too.

```bash
➜ curl localhost:9292
Akshay's Blog

➜ curl localhost:9292/articles
All Articles

➜ curl localhost:9292/articles/1
First Article

➜ curl localhost:9292/articles/x
no route found for /articles/x

➜ curl localhost:9292/random-url
no route found for /random-url
```

We have a functioning router implementation. Woohoo!

## But It Doesn't Look Like Rails!

At the start of the post, I promised the following router API that looked similar to what we have in Rails.

![rails-like-router.png](https://writesoftwarewell.com/media/yx6pcqsj2inn8s5rl54xprtcu0ps.png "Rails-like Router")

The current implementation doesn't look like that at all!

I know, I know. I decided to build the simplest router first as jumping directly in the above implementation would've meant compressing a lot of things together. But now that we have a simple and functioning router, we can refactor and improve it to make it more Rails-like in three simple steps:

## Step 1: Refactor the Router

Let's make a few small changes to the router, so it looks like this.

```ruby
# weby/router.rb

require 'singleton'

class Router
  include Singleton  # 1

  attr_reader :routes

  class << self
    def draw(&blk)  # 2
      Router.instance.instance_exec(&blk)  # 3
    end
  end

  def initialize
    @routes = {}
  end

  def get(path, &blk)
    @routes[path] = blk
  end

  def build_response(path)
    handler = @routes[path] || ->{ "no route found for #{path}" }
    handler.call
  end
end
```

Three important things to note:

1. I've made the&nbsp;`Router`&nbsp;class a&nbsp;[Singleton](https://refactoring.guru/design-patterns/singleton)&nbsp;so we always have a single instance to work with. Refer the&nbsp;[`Singleton`](https://ruby-doc.org/3.2.0/stdlibs/singleton/Singleton.html)[&nbsp;documentation](https://ruby-doc.org/3.2.0/stdlibs/singleton/Singleton.html)&nbsp;to learn more about how it works. In short, the Singleton pattern ensures that a class has only one globally accessible instance.
2. Added a&nbsp;`draw`&nbsp;method on the&nbsp;`Router`&nbsp;class so we could call it as&nbsp;`Router.draw`. This is a syntactic sugar to mimic Rails.
3. The&nbsp;`draw`&nbsp;method accepts a block and executes that block in the context of the instance of the&nbsp;`Router`&nbsp;class.&nbsp;[**This is exactly what the Rails Router does.**](/understanding-rails-router-why-what-how#understanding-how-instanceexec-works)&nbsp;Refer to the&nbsp;[`instance_exec`&nbsp;documentation](https://ruby-doc.org/3.2.0/BasicObject.html#method-i-instance_exec)&nbsp;to learn how it works.

Now, let's put this&nbsp;`Router`&nbsp;class to good use by creating the routes in a separate file.

## Step 2: Create the Routes

In the spirit of Rails, let's create a&nbsp;`config/routes.rb`&nbsp;file so we have a Rails-like structure. This file contains our application routes.

```ruby
# config/routes.rb

require_relative '../router'

Router.draw do
  get('/') { "Akshay's Blog" }
  
  get('/articles') { 'All Articles' }
  
  get('/articles/1') { "First Article" }
end
```

Note that we're calling the&nbsp;`draw`&nbsp;method on the&nbsp;`Router`&nbsp;and passing a block. Ruby will execute this block (code within&nbsp;`do..end`&nbsp;above) in the context of the instance of the&nbsp;`Router`. Hence, the&nbsp;`self`&nbsp;object in that block will be the&nbsp;`Router`.

The above code is similar to:

```ruby
router = Router.new

router.get('/') { "Akshay's Blog" }

# and so on...
```

**Don't you just love metaprogramming in Ruby?**

> If you're curious to learn more about metaprogramming, check out the following article: [Metaprogramming in Ruby](/metaprogramming-ruby)

There's only one thing remaining. Use those routes!

## Step 3: Update the Application to use New Routes

Since we have defined the routes elsewhere, we don't need them in the application constructor. Let's remove them. In fact, we can remove the whole constructor!

Here's the new&nbsp;`app.rb`&nbsp;file. Much cleaner, right?

```ruby
# weby/app.rb

require_relative './config/routes'

class App
  def call(env)
    headers = { 'Content-Type' => 'text/html' }
    
    response_html = router.build_response(env['PATH_INFO'])
    
    [200, headers, [response_html]]
  end

  private
    def router
      Router.instance
    end
end
```

Note that we're using the&nbsp;`Router.instance`&nbsp;method added by the&nbsp;`Singleton`&nbsp;module to get the&nbsp;`Router`'s instance.

That's it. Restart the application and give it a try. Everything should work as expected.

We could stop here, but there's one small improvement we can do to make our Router more flexible and powerful.

## Let's Pass the HTTP Environment to Routes

Right now, our routes cannot access the incoming request, i.e. the&nbsp;`env`&nbsp;hash. It would be really nice if they could use&nbsp;`env`&nbsp;to add more dynamic behavior. For example, you could access the cookies and session data in your handlers via the HTTP request.

Let's fix it.

> 💡Before reading the next section, can you try implementing this on your own? We have the&nbsp;`env`&nbsp;hash in the&nbsp;`app.rb`. How would you pass it to the handlers?

All we need to do is pass&nbsp;`env`&nbsp;to the&nbsp;`Router`&nbsp;and then further pass it to the handlers when we call it. Here's the changelog.

```ruby
# app.rb

response_html = router.build_response(env)

# router.rb

def build_response(env)
  path = env['PATH_INFO']
  handler = @routes[path] || ->(env) { "no route found for #{path}" }
  handler.call(env)  # pass the env hash to route handler
end

# config/routes.rb

get('/articles/1') do |env| 
  puts "Path: #{env['PATH_INFO']}"
  "First Article"
end
```

💡If you're curious how the above code works, especially how the handlers remember the&nbsp;`env`&nbsp;hash, read this:&nbsp;[capture variables outside scope](/ruby-block-proc-lambda-and-differences-between-them#capture-variables-outside-scope).

Now all our route handlers have access to the incoming HTTP request. Later, we'll wrap this&nbsp;`env`&nbsp;hash into a dedicated&nbsp;`Request`&nbsp;class for exposing a better API, just like the&nbsp;[`ActionDispatch::Request`](https://api.rubyonrails.org/classes/ActionDispatch/Request.html)&nbsp;class in Rails.

**That's a wrap. In the course (currently in beta), we'll explore the following topics:**

- Introduce controllers, models, and views, just like Rails!
- Improve the project structure and organization
- Add unit tests
- Handle errors and logging
- Process form inputs along with query strings into a&nbsp;`params`&nbsp;object
- Connect to the database to store and fetch data
- Add middleware to handle specific tasks like authentication
- and much more...

Trust me, it's going to be a lot of fun, so&nbsp;**stay tuned!!**

If you've liked what you've seen so far, and would like to enroll in the course, you can do so here:&nbsp;**Rails Companion**

