[Quicky] Unused routes for Rails 7.0 below

[Quicky] Unused routes for Rails 7.0 below

With Rails 7.1, you can list unused routes with:

./bin/rails routes --unused

For Rails 6.0, 6.1 and 7.0, below is a script I used in my project to find out unused routes. Apparently, I barrow it from ShakaCode. Thanks to them.

In conjunction with the self contained rails script shown before, here's the full modified script:

#!/usr/bin/env ruby
APP_PATH = File.expand_path("../../config/application",  __FILE__)
require File.expand_path("../../config/boot",  __FILE__)
require APP_PATH


unused_routes = {}

Rails.application.routes.routes.each do |r|
  name = r.requirements[:controller].to_s.camelize
  action = r.requirements[:action].to_s
  controller = "#{name}Controller"

  if Object.const_defined?(controller) && !controller.constantize.new.respond_to?(action)
    unless Dir.glob(Rails.root.join("app", "views", name.downcase, "#{action}.*")).any?
      unused_routes[controller] = [] if unused_routes[controller].nil?
      unused_routes[controller] << action

pp unused_routes

The script is in the file bin/unused_routes. And it's an executable (chmod +x bin/unused_routes).

With that, you only need to run the command below. No more need to remember or search for it, everything lives in your repository.