Posts

Showing posts from May, 2009

recognize_path to determine url hash from RESTful url

If you are using RESTful controllers for your application, same url can refer different actions in a controller based on the associated HTTP method. For instance let’s consider a URL http://your.host.com/messages/123 . Any request with this url with HTTP get will be paired with the show method of messages controller. Some other pairs are like HTTP put with update action, and HTTP delete with destroy action. Then how can you get a hash of controller and action from this url? In this situation recognize_path to the rescue. You can use ActionController::Routing::Routes .recognize_path(url, method) where url is the '/messages/123' part and method is anyone from GET, PUT, POST or DELETE. It will return a hash containning controller, action and other parameters, for example :id => 123 in the above case. By the way if you are thinking to trim the first part of the url just use as following url = 'http://your.host.com/messages/123' extracted_part = url.g