2

Given a method and path, I want to ask Rails how that request would be routed, and i want to be able to do this from console, and/or from a rake task. I figure this should be straightforward - ActionDispatch does this for every request, and the route testing methods obviously also do it.

(Currently: Rails 3.0.x, but for the gem I'm writing I will need to be able to do this in Rails 3.0 through 4.1, at minimum, and possibly in older versions as well.)

I've been trying a few things like this:

routes = ActionDispatch::Routing::RouteSet.new
routes.recognize_path('/my/path/23/edit')

or

Rails.application.routes.recognize_path('/my/path/23/edit')

In both cases, I get back "RuntimeError: route set not finalized".

I'm diving through the ActionDispatch code working it out slowly, but if anyone knows the answer off the top of their head it would save me considerable time. So, thank you!

Evan
  • 121
  • 1
  • 7
  • Using `Rails.application.routes.recognize_path` works fine on my system so the command is correct. Perhaps something isn't being setup properly? Where are you trying to make this call? – MCBama Jun 27 '14 at 17:01
  • On further investigation, there's a `finalize!` method (duh), but I get an empty route set when initialized as above. So it seems I'm missing something about the initialization of RouteSet. – Evan Jun 27 '14 at 17:07
  • @Micah: I'm trying to run this in console, at the moment, just to test it out. Once I get it working, it's going into a gem that analyzes records of request/response pairs to identify which unique routes are actually hit during those requests. – Evan Jun 27 '14 at 17:09
  • Apparently I get an empty route set: `1.8.7-head :037 > Rails.application.routes.routes => [] ` – Evan Jun 27 '14 at 17:09

1 Answers1

3

The canonical answer is actually as given in my question:

# GET request
Rails.application.routes.recognize_path('/some/path/63') 

# POST request
Rails.application.routes.recognize_path('/some/path', {:method => :post })

It looks like that wasn't working because I'd previously tried initializing RouteSet manually, which had interfered with the environment's ability to properly load the routes. When I restarted the console session, the above commands worked fine.

Evan
  • 121
  • 1
  • 7
  • Ahha so something was being setup incorrectly. Or more accurately the setup was being overwritten. Glad you figured it out. – MCBama Jun 27 '14 at 19:58