3

I am trying to write a script that can list all available routes and for each route, query the controller and action name (a bit like rake routes).

If I run Rails.application.routes.routes I can see the data is all there. I just can't seem to access it.

 @named_routes=
  {"root"=>
    #<ActionDispatch::Journey::Route:0x007fc2cb40a598
     @app=
      #<ActionDispatch::Routing::RouteSet::Dispatcher:0x007fc2cb40b448
       @controller_class_names=#<ThreadSafe::Cache:0x007fc2cb40b420 @backend={}, @default_proc=nil>,
       @defaults={:trailing_slash=>false, :controller=>"home", :action=>"show"},
       @glob_param=nil>,
     @constraints={:required_defaults=>[:trailing_slash, :controller, :action], :request_method=>/^GET$/},
     @decorated_ast=nil,
     @defaults={:trailing_slash=>false, :controller=>"home", :action=>"show"},

How do I access that hash tucked away in there with the controller name.

As a side, Is there a way to determine a path from this?

1 Answer 1

7

This should work if I understand your question correctly:

Rails.application.routes.routes.named_routes.values.map(&:defaults)

Then you can do something like this:

Rails.application.routes.routes.named_routes.values.map do |route|
  "#{route.defaults[:controller]}#{route.defaults[:action]}"
end      
Sign up to request clarification or add additional context in comments.

2 Comments

thank you my man, that worked a treat, minus the slight typo ;)
For rails 5 it has slightly changed. I used this to get all routes Rails.application.routes.named_routes.send(:routes).values

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.