views:

261

answers:

3

Within the scope of a Rails controller or a view: How can I query the Rails routing mechanism to turn a relative url string (eg "/controllername/action/whatever" into the controller class that would be responsible for handling that request?

I want to do something like this:

controllerClass = someMethod("/controllername/action/whatever")

Where contorllerClass is an instance of Class.

I don't want to make any assumptions about a routing convention eg. that the "controllername" in the above example is always the name of the controller (because it's not).

A: 

I don't know if there is a better way to do it but I would try to look at Rails' own code.

The routing classes have some assertion methods used on testing. They get a path and the expected controller and asserts it routes correctly.

Looking there should give you a good start on it.

http://api.rubyonrails.org/classes/ActionController/Assertions/RoutingAssertions.html#M000598

Specially this line

generated_path, extra_keys = ActionController::Routing::Routes.generate_extras(options, defaults)

Hope that helps.

Edit:

It looks like I pointed you to the opposite example.

You want path => controler/action

Then you should look at

http://api.rubyonrails.org/classes/ActionController/Assertions/RoutingAssertions.html#M000597

One way or another I think you can find your solution along those lines :)

Carlos Lima
+6  A: 

Building off Carlos there:

path = "/controllername/action/whatever"
c_name = ActionController::Routing::Routes.recognize_path(path)[:controller]
controllerClass = "#{c_name}_controller".camelize.constantize.new

will give you a new instance of the controller class.

Joel Meador
Darn! By the time SO told me 'an answer has been posted' it was 19 minutes past it.. +1 from me for the correct answer..
Swanand
+1  A: 

ActionController::Routing::Routes.recognize_path "/your/path/here"

Would print:

{:controller=>"corresponding_controller", :action=>"corresponding_action" } # Plus any params if they are passed

Swanand