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(/\?.*$/,'')
Nice post.