Skip to content

Instantly share code, notes, and snippets.

@thinkerbot
Created August 7, 2012 16:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thinkerbot/3286702 to your computer and use it in GitHub Desktop.
Save thinkerbot/3286702 to your computer and use it in GitHub Desktop.
Remove unused routes from config/routes.rb
#!/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"
@thinkerbot
Copy link
Author

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.

  resource :thing
  resources :things
  resource :thing, :controller => 'controller'
  resuorces :things, :controller => 'controller'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment