Skip to content

Instantly share code, notes, and snippets.

@coryodaniel
Last active May 5, 2020 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coryodaniel/93c983f0e09d9f0db79918f695e184fa to your computer and use it in GitHub Desktop.
Save coryodaniel/93c983f0e09d9f0db79918f695e184fa to your computer and use it in GitHub Desktop.
find unused rails routes
require "action_dispatch"
require "json"
# RIP your CPU if you have a lot of traffic. Check out the parallel gem w/ multiple processes to speed this up.
list_of_url_paths_visited = File.readlines("list_of_url_paths_visited.txt", chomp: true)
# YMMV
# the 2nd or 3rd column will be the path w/ awk
rake_routes_paths = `rake routes | awk '{if ($2 ~ /\\//) {print $2} else if ($3 ~ /\\//) {print $3}}'`.split("\n")
# path_template is the paths in rake routes like /users/:id etc...
routes = rake_routes_paths.reduce({}) do |acc, path_template|
acc[path_template] = ActionDispatch::Journey::Path::Pattern.from_string(path_template)
acc
end
# "Hey, this could have been a reduce!1!!" 👍 I know.
hit_stats = Hash.new(0)
list_of_url_paths_visited.each do |request|
matched = routes.find {|path_template, path| path.match(request)}
if matched
path_template = matched[0]
hit_stats[path_template] += 1
end
end
hit_stats_json = JSON.dump(hit_stats)
hit_stats_file = File.open("stats.json", "w+")
hit_stats_file.puts(hit_stats_json)
rake_routes_visited = hit_stats.values
rake_routes_unvisited = rake_routes_paths - rake_routes_visited
# "Hey, this doesn't need to be JSON!!1!!!!" 👍 I know.
rake_routes_unvisited_json = JSON.dump(rake_routes_unvisited)
rake_routes_unvisited_file = File.open("unvisited.json", "w+")
rake_routes_unvisited_file.puts(rake_routes_unvisited_json)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment