Skip to content

Instantly share code, notes, and snippets.

@jaynetics
Last active May 15, 2023 19:38
Show Gist options
  • Select an option

  • Save jaynetics/69dfd9e417ad207c1695c9adbd0c51b0 to your computer and use it in GitHub Desktop.

Select an option

Save jaynetics/69dfd9e417ad207c1695c9adbd0c51b0 to your computer and use it in GitHub Desktop.
Find rails routes with no corresponding controller action
desc 'Finds unused routes (routes with no corresponding controller action)'
task find_unused_routes: :environment do
checked_actions = %i[create destroy edit index new show update]
Rails.application.eager_load!
endpoints = Rails.application.routes.routes.map do |route|
ActionDispatch::Routing::RouteWrapper.new(route).endpoint
end
checked_endpoints = endpoints.
grep(/#(?:#{checked_actions.join('|')})\z/).
grep_v(/^(?:action_|active_|rails)/)
controllers = ObjectSpace.each_object(Class).select do |klass|
klass < ActionController::Base
end
controller_actions = controllers.flat_map do |ctrl|
actions = ctrl.public_instance_methods & checked_actions
actions.map do |action|
"#{ctrl.name.underscore.chomp('_controller')}##{action}"
end
end
unused = (checked_endpoints - controller_actions).uniq
puts unused.sort, "#{unused.count} unused routes, may include false positives"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment