Which route matches my path?

March 20th, 2009

I’ve been thrown headlong into a big Rails app after a couple of years of very minimal Rails exposure, and it’s proving to be Very Interesting™

This particular app has pretty complex routing, and since there have been a lot of developments since last I wrote a complex Rails app, I don’t necessarily trust myself to be able to mentally translate a path into a route into a controller/action pair. With some help and pointers from Yossef Mendelssohn and the internets, I threw together a rake task to help.

It should be noted that this is fragile. I don’t know what happens if you put in a bogus path. I don’t care, really… it’s good enough for my present needs, I’ll update it if necessary.

Updated: now shows matches for all supported verbs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
namespace :routes do
  task :matching, [:path] => :environment do |_, args|
    puts # blank line
    puts "Routing match for #{args.path}"
    puts "=" * 72
    
    results = {}
    
    ActionController::Routing::HTTP_METHODS.each do |verb|
      begin
        results[ verb ] = ActionController::Routing::Routes.recognize_path args.path, :method => verb
      rescue ActionController::MethodNotAllowed => e
        puts "#{verb.to_s.upcase} not supported."
        next
      end
    end
    
    puts # blank line
    
    results.each do |verb, result|
      controller = result.delete( :controller )
      action     = result.delete( :action     )
      
      puts "Verb:       #{verb.to_s.upcase}"
      puts "Controller: #{controller}"
      puts "Action:     #{action}"
      puts "Parameters: #{result.inspect}"
      puts # blank line
    end
  end
end

Getting back into the swing of things probably means more blogging… which will make me happy, anyway. I’m tired of neglecting this thing. Keep your eyes peeled!

Sorry, comments are closed for this article.