Hackernoon logoGet Unused Routes of Large Rails App 🛠 by@rishipithadiya

Get Unused Routes of Large Rails App 🛠

Author profile picture

@rishipithadiyaRishi Pithadiya

Finding happiness in words, food, places & untold stories ✌🏼

After a few years of continuous development, your rails application becomes larger and it’s good practice to do some cleanup. One of the most obvious cleanups is cleaning up unused routes.

As your rails application grows, at the time of adding a route for new action, developers sometimes add 

resources :objects
 file rather than adding a single member or collection route which creates unnecessary routes at runtime 😖

For example,

Rails.application.routes.draw do
  resources :users

Writing above code will create the following routes -

But, it might be possible that we are not using all of the above methods, or we need only 

 methods in our Users controller like -

class UsersController < ApplicationController
  def new

  def create

  def show

So, it’s the most obvious process to inspect your 

 file from time to time and clean it if necessary.

Inspecting each route and its corresponding action took so much time and it’s next to impossible thing when the application is so large 😞

Now, there are few ruby gems available in the market which can do it for you, but again adding additional gem requires extra load in your gemfile of your large application.

Another solution is to make a simple script which compares routes and associated actions available in controllers and list down all possible unused routes of our large application so that we can clean 

 file and remove routes that are not needed.

Have a look at following a small ruby script -

unused_routes = {}

# Iterating over all non-empty routes from RouteSet
Rails.application.routes.routes.map(&:requirements).reject(&:empty?).each do |route|
  name = route[:controller].camelcase
  next if name.start_with?("Rails")

  controller = "#{name}Controller"

  if Object.const_defined?(controller) && !controller.constantize.new.respond_to?(route[:action])
    # Get route for which associated action is not present and add it in final results
    unless Dir.glob(Rails.root.join("app", "views", name.downcase, "#{route[:action]}.*")).any?
      unused_routes[controller] = [] if unused_routes[controller].nil?
      unused_routes[controller] << route[:action]

puts unused_routes 
# {"UsersController"=>["edit", "update", "update", "destroy"]}

For getting unused routes for your rails app, all you need to do is to copy above code in your rails console or you can paste above code in single file 

 in the root directory of your Rails application and run it using the following command -

$> ruby get-unused-routes.rb 

Using above small script we’re able to get all unused routes of our large rails application, we don’t use any Gem/Plugin to achieve this 🥳

References -


Join Hacker Noon

Create your free account to unlock your custom reading experience.