Created
August 7, 2012 16:06
-
-
Save thinkerbot/3286702 to your computer and use it in GitHub Desktop.
Remove unused routes from config/routes.rb
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
#!/bin/bash | |
######################################################################## | |
# Add to Gemfile: | |
# | |
# gem 'traceroute', '= 0.2.2' | |
# | |
# Then: | |
bundle install | |
printf "*** BEFORE ***\n" | |
time bundle exec rails runner "puts :hello" | |
bundle exec rake traceroute | | |
sed -ne '/^Unused/,/^Unreachable/p' | | |
sed -e '/^U/d' | | |
bundle exec ruby -e ' | |
require "active_support/inflector" | |
ACTIONS = %w{index new create show edit update destroy}.map(&:to_sym) | |
def limit_str(unused_actions) | |
only_actions = ACTIONS - unused_actions | |
if only_actions.empty? | |
"" | |
else | |
except_actions = ACTIONS & unused_actions | |
if except_actions.length < only_actions.length | |
", :except => #{except_actions.inspect}" | |
else | |
", :only => #{only_actions.inspect}" | |
end | |
end | |
end | |
resources = Hash.new {|hash, key| hash[key] = [] } | |
while line = gets | |
resource, unused_action = line.chomp("\n").split("#") | |
resources[resource.strip] << unused_action.to_sym | |
end | |
File.open("config/routes.rb") do |io| | |
io.each_line do |line| | |
case line | |
when /resource :(\w+)(?:, :controller => '\''(.*?)'\'')?/ | |
if unused_actions = resources.delete($2 || $1.pluralize) | |
line.sub!(/resource :#{$1}/, "resource :#{$1}#{limit_str(unused_actions)}") | |
end | |
when /resources :(\w+)(?:, :controller => '\''(.*?)'\'')?/ | |
if unused_actions = resources.delete($2 || $1) | |
line.sub!(/resources :#{$1}/, "resources :#{$1}#{limit_str(unused_actions)}") | |
end | |
end | |
puts line | |
end | |
end | |
$stderr.puts "Leftover:" | |
$stderr.puts resources.inspect | |
' > new_routes.rb | |
mv new_routes.rb config/routes.rb | |
printf "*** AFTER ***\n" | |
time bundle exec rails runner "puts :hello" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Be advised this script is brittle. At the end it prints out any routes that were not updated. In our case that happened because the non-updated route was not written with one of these patterns of symbols and strings.