# Custom URL Helpers in Rails with the direct Method

*Published on February 11, 2024*

Tags: Rails Internals

---


I recently bought 37signals' first&nbsp;[ONCE](https://once.com/)&nbsp;product,&nbsp;[Campfire](https://once.com/campfire). I think it's a fantastic deal to get to read the source code of a Rails app running in production, from a world-class Rails development team and&nbsp;[DHH himself](https://world.hey.com/dhh/patek-levels-of-finishing-467e5dc0). I also attended a code walkthrough with David on Friday, and seeing his energy and passion about the nuts and bolts of the code alone was worth the entry price of $299.

> 💥 So I’ve been sweating those details a lot with ONCE #1. Regularly reading through the entire 7,412 lines of code to polish spacing, pick slightly better model names, and correct cohesion issues. And every time I do, I usually also find other small quality issues that’ll lead to a better product which fewer people will have issues with.  
>   
> \- David Heinemeier Hansson, in&nbsp;[**Patek levels of finishing**](https://world.hey.com/dhh/patek-levels-of-finishing-467e5dc0)

I don't plan to use the chat application right away, and haven't even installed it yet, as I've been busy digging into the source code for the past few days, which is incredibly simple yet powerful and very, very expressive.

One of the very first things I do whenever I come across a new Rails codebase is to open the routes file and see what are the points of interaction (i.e. route endpoints) with the application.

_Routing is such an important concept in Rails that I wrote a ~5000 word post on it:_&nbsp;[_Understanding the Rails Router: Why, What, and How_](/understanding-rails-router-why-what-how)[  
](/understanding-rails-router-why-what-how)

Anyway, while reading Campfire's&nbsp;`routes.rb`&nbsp;file, I came across a new method called&nbsp;`direct`&nbsp;that I'd never seen before.

```ruby
# config/routes.rb

direct :fresh_user_avatar do |user, options|
  route_for :user_avatar, user, v: user.updated_at.to_fs(:number)
end

direct :fresh_account_logo do |options|
  route_for :account_logo, v: Current.account&.updated_at&.to_fs(:number)
end
```

You may have seen and used this method before, but I'm sure there're many like me who don't know what it does and have never used it before. So, in this post, we'll take a look at this&nbsp;`direct`&nbsp;method.&nbsp;**What is it, and what does it do?**

Let's dig in.

* * *

## Named Routes and Route Helpers

You know that whenever you create standard routes, Rails provides two helper methods such as&nbsp;`xxx_path`&nbsp;and&nbsp;`xxx_url`&nbsp;which&nbsp;[generate the corresponding URL for that route](/understanding-rails-router-why-what-how#named-routes), using the provided parameters. For example,

- `photos_path`&nbsp;returns&nbsp;`/photos`
- `new_photo_path`&nbsp;returns&nbsp;`/photos/new`
- `edit_photo_path(:id)`&nbsp;returns&nbsp;`/photos/:id/edit`&nbsp;(e.g.&nbsp;`edit_photo_path(10)`&nbsp;returns&nbsp;`/photos/10/edit`)

In addition, you can pass the&nbsp;`:as`&nbsp;option to a route to give a specific name for the route. When you name a route, Rails will automatically generate helper methods to generate URLs for that route. These methods are called&nbsp;`name_url`&nbsp;or&nbsp;`name_path`, where&nbsp;`name`&nbsp;is the value you gave to the&nbsp;`:as`&nbsp;option.

For example, the following route definition will generate&nbsp;`logout_path`&nbsp;and&nbsp;`logout_url`&nbsp;helper methods that return&nbsp;`/exit`&nbsp;and&nbsp;`https://localhost:3000/exit`&nbsp;respectively.

```ruby
get 'exit', to: 'sessions#destroy', as: :logout
```

With that background, let's try to understand the&nbsp;`direct`&nbsp;method.

## What is the direct Method in the Rails Router?

**The**&nbsp;**`direct`**&nbsp;**method lets you define custom URL helpers.**&nbsp;You define the helper name first, and then define the URL that this helper will return when called. Any parameters passed to the helper method are directly passed to the block.

```ruby
direct :course_landing_page do
  "https://courses.writesoftwarewell.com/"
end

# >> course_landing_page_url
# => "https://courses.writesoftwarewell.com/"

direct :greeting_page do |user|
  "https://writesoftwarewell.com/#{user.name}"
end

# >> greeting_page_path(matz)
# => "/yukihiro"
```

Using the&nbsp;`direct`&nbsp;method, you can override and/or replace the default behavior of routing helpers in Rails.

The above example was very simple:&nbsp;**just define the helper name and return the URL**. However, as with everything in Rails, this simple API is also very flexible. In addition to the string URL, which is treated as a generated URL, you can also return one of the following options, for more powerful customizations:

1. A Hash, e.g.&nbsp;`{ controller: "page", action: "index" }`
2. An Array, which is passed to&nbsp;`polymorphic_url`
3. An Active Model instance, or
4. An Active Model class

In fact, the return value of the block must be a valid argument for the&nbsp;[`url_for`](https://api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html#method-i-url_for)&nbsp;method. This method actually builds the URL string.

```ruby
direct :previewable do |file|
  [ file, slug: file.slug ]
end

direct :sales do
  { controller: 'LandingPages', action: 'sales', subdomain: 'pay' }
end
```

To learn more about how you can use the above options, I suggest reading the&nbsp;[documentation for the&nbsp;`url_for`&nbsp;method](https://api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html#method-i-url_for).

What's more, you can even call other URL helpers. However, an important thing to keep in mind is not to call the same custom URL helper you're defining. Otherwise, it will keep calling itself, resulting in the notorious Stack Overflow error.

```ruby
direct :course_landing_page do
  # Warning: Don't Do This!!!
  course_landing_page_path
end
```

## Behind the Scenes: Reading the Source

As always, let's open the Rails source code and see how this method is implemented. Surprisingly, it's not long, just four lines of code:

```ruby
# actionpack/lib/action_dispatch/routing/mapper.rb

def direct(name, options = {}, &block)
  unless @scope.root?
    raise RuntimeError, "The direct method can't be used inside a routes scope block"
  end
  
  @set.add_url_helper(name, options, &block)
end
```

The very first thing we notice is that the&nbsp;`direct`&nbsp;method cannot be used inside of a scope block such as&nbsp;`namespace`&nbsp;or&nbsp;`scope`. If you do it anyway, Rails will raise an error.

Finally,&nbsp;`direct`&nbsp;delegates to the&nbsp;[`add_url_helper`](https://github.com/rails/rails/blob/main/actionpack/lib/action_dispatch/routing/route_set.rb#L150)&nbsp;method to create a custom URL helper, which is an internal method. It defines the&nbsp;`name_path`&nbsp;and&nbsp;`name_url`&nbsp;helpers, given a&nbsp;`name`.

If you're interested in learning about the internals of the Rails Router, check out the following section:&nbsp;[**How Rails implements the beautiful routing DSL**](/understanding-rails-router-why-what-how#digging-deeper-router-internals)**.**

## **Revisiting Campfire**

Let's get back to the two Campfire routes we saw earlier. With everything we've just learned,&nbsp;**can you try to guess what these routes do and in what context they can be used?**

```ruby
# config/routes.rb

direct :fresh_user_avatar do |user, options|
  route_for :user_avatar, user, v: user.updated_at.to_fs(:number)
end

direct :fresh_account_logo do |options|
  route_for :account_logo, v: Current.account&.updated_at&.to_fs(:number)
end
```

Let's take the first route. It defines two helper methods named&nbsp;`fresh_user_avatar_path`&nbsp;and&nbsp;`fresh_user_avatar_url`. In addition, it accepts two parameters,&nbsp;`user`&nbsp;and&nbsp;`options`.

Inside the block, it calls the&nbsp;[`route_for`](https://api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html#method-i-route_for)&nbsp;method. Let's inspect the Rails source to see what this method does:

```ruby
# action_dispatch/routing/url_for.rb

def route_for(name, *args)
  public_send(:"#{name}_url", *args)
end
```

It simply calls the helper method, passing any arguments passed to it. So our helper&nbsp;`fresh_user_avatar_url`&nbsp;is indirectly calling the&nbsp;`user_avatar_url`&nbsp;helper. The route for this helper is defined just a few lines above:

```ruby
resources :users, only: :show do
  scope module: "users" do
    resource :avatar, only: %i[ show destroy ]
  end
end
```

Here's an example where it's used in the codebase, to display the user's avatar:

```ruby
# app/views/users/show.html.erb

<%= image_tag fresh_user_avatar_path(@user), role: "presentation", class: "avatar" %>
```

And that's how Campfire uses the&nbsp;`direct`&nbsp;method in the Rails router to create a custom helper that returns the user's avatar URL.

**P.S.:**&nbsp;I still haven't figured out the purpose of the option passed to the helper,&nbsp;`v: user.updated_at.to_fs(:number)`&nbsp;as I just couldn't find out where it's being used in the codebase. If any 37signals developers are reading this post and know the answer, please enlighten me.

> 💡**Update:** The&nbsp;`v`&nbsp;option is used for invalidating the cached image and fetching the latest version of the avatar. Whenever the user updates their profile picture, the generated URL will be different, which will bust the cache and return a fresh copy of the avatar.

