find unused rails routes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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