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
Any request with this url with
You can use
where url is the
By the way if you are thinking to trim the first part of the url just use as following
However you can do the reverse operation by using
Hope you can be in rest using
Thank you
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.gsub(/.*\/\/[^\/]+/,'')then
ActionController::Routing::Routes.recognize_path(extracted_path,:method=>:get)
However you can do the reverse operation by using
ActionController::Routing::Routes.generate(url_hash)
method to get url in string form from a hash.Hope you can be in rest using
recognize_path
for restful urls :-)Thank you
Really interesting way of reusing the rails library. I think this might be useful for logging, when an application needs to log all controller/actions/params. Also, it may be useful for parsing the URL and then taking required actions.
ReplyDeleteGood post. Keep it up!
Its good to see you r in blog again. Though i didn't und the topic as it wasn't related to my expertise. But i guess it must be a good one coz this is from a smart dude.
ReplyDeletehowever keep going on.