Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 887
Joel Avatar asked Jun 29 '09 07:06

Joel


1 Answers

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.

like image 120
Joel Meador Avatar answered Oct 24 '22 00:10

Joel Meador