How to determine the given controller class url

Within a Rails controller or view: How can I request a Rails routing mechanism to include a relative url string (for example, "/ controllername / action / whatever" in the controller class that will be responsible for processing this request?

I want to do something like this:

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

Where contorllerClass is an instance of a class.

I do not want to make any assumptions regarding the routing agreement, for example. that "controllername" in the above example is always the name of the controller (because it is not).

+6
ruby-on-rails
source share
3 answers

Form Carlos there:

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

will provide you with a new instance of the controller class.

+11
source share

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

It will be printed:

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

+1
source share

I don't know if there is a better way to do this, but I will try to look at my own Rails code.

Routing classes use some of the approval methods used in testing. They get the path and expected controller and claim that it is routed correctly.

A look there should give you a good start.

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 this helps.

Edit:

Looks like I pointed you to the opposite example.

Do you want path => controler / action

Then you should look

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

Anyway, I think you can find your solution on these lines :)

0
source share

All Articles