Skip to content

Instantly share code, notes, and snippets.

@rzane
Last active November 1, 2024 13:43
Show Gist options
  • Save rzane/51e8b8886fc916831c3dd9fe92cdf09d to your computer and use it in GitHub Desktop.
Save rzane/51e8b8886fc916831c3dd9fe92cdf09d to your computer and use it in GitHub Desktop.
Detect unused routes (Rails 7.0)
# frozen_string_literal: true
# Usage: bin/rails runner unused_routes.rb
def action_exists?(controller, action)
controller_class = "#{controller.camelize}Controller".constantize
controller_class.public_instance_methods.include?(action.to_sym)
rescue NameError
false
end
def view_exists?(controller, action)
Rails.root.join("app/views/#{controller}/#{action}.html.erb").exist?
end
routes = Rails.application.routes.routes.filter_map do |route|
controller = route.requirements[:controller] or next
action = route.requirements[:action] or next
next if action_exists?(controller, action)
next if view_exists?(controller, action)
route
end
formatter = ActionDispatch::Routing::ConsoleFormatter::Expanded.new
inspector = ActionDispatch::Routing::RoutesInspector.new(routes)
puts inspector.format(formatter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment