How to determine Controller class given URL string

ruby-on-rails

Solution

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.

Problem

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

Original source