Skip to Content

Rails - Get unused routes of your rails applications

Posted on

Learned from Get unused routes of your rails app

When our rails applicaiton become larger, there are many unused routes appeared. You define it in routes.rb file, but you don’t define action in controllers.

This script will help to list down all possible unused routes

unused_routes = {}

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

  controller = "#{name}Controller"

  if Object.const_defined?(controller) && ![: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
# {"HomeController"=>["edit", "update", "update", "destroy"]}

Just put this code to rails console, or create a file get-unused-routes.rb in the root directory of Rails application and run ruby get-unused-routes.rb

comments powered by Disqus