Rails 7.1 Adds --unused Option To Detect Dormant Routes.

As projects grow and undergo refactoring, some routes can become obsolete, leading to cluttered routing files and potential confusion. These unused or dormant routes are routes defined in the configuration but not actively used in the application.

Dormant routes (extraneous routes)

Dormant routes are defined routes that are not linked to any controllers, actions, or views. These unused routes can accumulate over time, making it difficult to manage and understand the routing configuration.

Before

Identifying unused routes in a Rails application was previously a manual process. Since Rails did not provide built-in support for detecting dormant routes, developers had to rely on third-party gems (such as traceroute) or manually inspect routes, controllers, and views, which was both tedious and error-prone.

Rails.application.routes.draw do
  get 'users/index'
  get 'users/show'
  get 'unused_route', to: 'users#unused'
end

In this routing configuration, unused_route is defined but not actually used in the application. This route could have been added as part of an old feature, during development, or by mistake. Over time, such routes accumulate, creating dormant routes that contribute to clutter in the routing file, making it harder to maintain and understand the codebase.

After

Rails 7.1 introduced the routes –unused option, making it easier to detect dormant routes automatically.

bin/rails routes --unused

Sample output if an unused route is found,

Found 1 unused route:

Prefix      Verb   URI Pattern            Controller#Action
unused_route GET  /unused_route(.:format) users#unused

If no unused routes found,

No unused routes found.

Filtering Unused Routes:

The routes --unused command includes options to help refine results:

-g (grep):

Filter by specific route patterns (e.g., action or controller).

bin/rails routes --unused -g unused_route

Found 1 unused route:

Prefix       Verb  URI Pattern            Controller#Action
unused_route GET  /unused_route(.:format) users#unused

If no match is found,

bin/rails routes --unused -g posts

No unused routes found for this grep pattern.
-c (controller name):

Filter by controller name.

bin/rails routes --unused -c users

Found 1 unused route:

Prefix      Verb   URI Pattern            Controller#Action
unused_route GET  /unused_route(.:format) users#unused

If no unused routes are found for the specified controller,

bin/rails routes --unused -c posts

No unused routes found for this controller.

Benefits of routes –unused

The --unused option in Rails 7.1 streamlines route management by helping to identify and remove obsolete routes. This improves application maintainability, enhances performance, and reduces security risks by limiting unnecessary endpoint exposure.

Need help on your Ruby on Rails or React project?

Join Our Newsletter