Blog

Rails Tip: Inverse of #url_for

· 1 comment

Rails provides a highly functional URL-to-action routing system. The core method used by #redirect_to and #link_to when generating URL’s is #url_for.

So, the question eventually pops up:
What is the opposite of #url_for?

The answer is built-in to Rails, used at the beginning of every request in dispatcher.rb to generate a route from the URL. It’s stashed inside a :nodoc: section of Rails’ source:

ActionController::Routing::Routes.recognize_path

Depending on context, your call to #recognize_path may need to be prefixed by the top-level class prefix “::”.

#recognize_path only works on the path part of the URL. Passing a full URL with the protocol, hostname or query string will cause throw ActionController::RoutingError. Make sure you cleanse the path of those URL components.

In my case, usage looks like:

return_to_hash = ::ActionController::Routing::Routes.recognize_path url.gsub(/\?.*$/,'')

Posted on Wednesday, January 23th 2008 at 15:48 under . Tagged , , , , , , .

1 Comment

Gravatar

Nice post.

Post a comment