Skip to content

Instantly share code, notes, and snippets.

@speed-of-light
Last active December 21, 2015 15:49
Show Gist options
  • Select an option

  • Save speed-of-light/6329006 to your computer and use it in GitHub Desktop.

Select an option

Save speed-of-light/6329006 to your computer and use it in GitHub Desktop.
rails rake color routes
desc 'Pretty version on rails rake routes.'
# modified from https://github.com/nicooga/color_routes
# put this file under your [rails.root]/lib/tasks/
# tested under rails 4.0.0
# Default usage:
# $>>> rake color_routes
# Routes with specific controller
# $>>> rake color_routes controller=devise/sessions
# Routes with multiple filters
# $>>> rake color_routes path=login verb=GET
# See the demo in the images
EMK="\033[1;30m"
EMR="\033[1;31m"
EMY="\033[1;33m"; EBY="\e[1;43m"
EMB="\033[1;34m"
EMM="\033[1;35m"
EMC="\033[1;36m"
EMW="\033[1;37m"
NOCOLOR = "\033[0m"
task :color_routes => :environment do
Rails.application.reload_routes!
all_routes = Rails.application.routes.routes.to_a
all_routes.reject! { |route| route.verb.nil? || route.path.spec.to_s == '/assets' }
# all_routes.select! { |route| ENV['CONTROLLER'].nil? || route.defaults[:controller].to_s == ENV['CONTROLLER'] }
all_routes.select! { |route| ENV['controller'].nil? || route.defaults[:controller].to_s == ENV['controller'] }
all_routes.select! { |route| ENV['verb'].nil? || route.verb === ENV['verb'] }
all_routes.select! { |route| ENV['path'].nil? || (route.path.spec.to_s.include? ENV['path']) }
all_routes.select! { |route| ENV['action'].nil? || route.defaults[:action].to_s == ENV['action'] }
max_widths = {
names: (all_routes.map { |route| route.name.to_s.length }.max),
verbs: (6),
paths: (all_routes.map { |route| route.path.spec.to_s.length }.max),
controllers: (all_routes.map { |route| route.defaults[:controller].to_s.length }.max),
actions: (all_routes.map { |route| route.defaults[:action].to_s.length }.max)
}
hs = "#{'name'.rjust(max_widths[:names])} | #{'verb'.center(max_widths[:verbs])} | " +
"#{'path'.ljust(max_widths[:paths])} | #{'action'.ljust(max_widths[:actions])}"
puts EMW + hs + NOCOLOR
all_routes.group_by { |route| route.defaults[:controller] }.each_value do |group|
cs = group.first.defaults[:controller].to_s
puts EBY + EMK + "CONTROLLER: " + EMW + cs + ' '.ljust(hs.size - 12 - cs.size) + NOCOLOR
group.each do |route|
name = EMC + route.name.to_s.rjust(max_widths[:names]) + NOCOLOR
verb = EMY + route.verb.inspect.gsub(/^.{2}|.{2}$/, "").center(max_widths[:verbs]) + NOCOLOR
path = EMR + route.path.spec.to_s.ljust(max_widths[:paths]).gsub(/\.?:\w+/){|s|EMB + s + EMR} + NOCOLOR
action = EMW + route.defaults[:action].to_s.ljust(max_widths[:actions]) + NOCOLOR
puts "#{name} | #{verb} | #{path} | #{action}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment