Joel
Joel

Reputation: 11851

How to determine Controller class given URL string

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).

Upvotes: 6

Views: 2830

Answers (3)

user1976
user1976

Reputation:

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.

Upvotes: 12

Carlos Lima
Carlos Lima

Reputation: 4182

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 :)

Upvotes: 0

Swanand
Swanand

Reputation: 12426

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

Would print:

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

Upvotes: 1

Related Questions