Skip to content

Instantly share code, notes, and snippets.

@joaopfsilva
Created September 20, 2019 06:48
Show Gist options
  • Save joaopfsilva/6f39989cf9c83cc8e7411dbf0d43dbaa to your computer and use it in GitHub Desktop.
Save joaopfsilva/6f39989cf9c83cc8e7411dbf0d43dbaa to your computer and use it in GitHub Desktop.
Check unused routes
# Download this into the root folder of your Rails project & run it with "ruby check-routes.rb"
# Originaly created by https://gist.githubusercontent.com/matugm/c298767ad1d97a52f76630bfc03008a1/raw/d1bfa23a0bf4ab24cf295eea030f4e3dccf653d7/check-routes.rb
require_relative "config/environment"
Rails.application.eager_load!
results =
Rails.application.routes.routes.map(&:requirements).reject(&:empty?).map do |r|
name = r[:controller].camelcase
controller = "#{name}Controller"
controller_with_action = "#{name}##{r[:action]}"
if Object.const_defined?(controller)
controller_instance = controller.constantize.new
else
next { controller_with_action => false }
end
next if name.start_with?("Rails")
if controller_instance.respond_to?(r[:action])
{ controller_with_action => true }
else
{ controller_with_action => Dir.glob(Rails.root.join("app", "views", name.downcase, "#{r[:action]}.*")).any? }
end
end
unused_controller_actions = results.reject(&:blank?).reject { |r| r.values.first }.uniq
if unused_controller_actions.empty?
puts "#{Rails.application.routes.routes.size} total routes. No unused routes found!"
else
puts "Unused routes found (#{unused_controller_actions.size})"
unused_controller_actions.map(&:first).map(&:first).each { |name| puts " " + name }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment