6

I am looking for method for parsing route path like this:

ActionController::Routing.new("post_path").parse
#=> {:controller => "posts", :action => "index"}

It should be opposite to url_for

Upd
I've found out: What is the opposite of url_for in Rails? A function that takes a path and generates the interpreted route?

ActionController::Routing::Routes.recognize_path("/posts")

So now I need to convert posts_path into "/posts"

Community
  • 1
  • 1
fl00r
  • 82,987
  • 33
  • 217
  • 237

2 Answers2

12

In Rails 3 you can do the following:

Rails.application.routes.recognize_path "/accounts/1"
# {:action=>"show", :controller=>"accounts", :id=>"1"}

Using ActionController::Routing::Routes.recognize_path kept throwing

ActionController::RoutingError Exception: No route matches "/accounts/1

Jeff
  • 13,943
  • 11
  • 55
  • 103
Matt Simpson
  • 492
  • 5
  • 5
  • Note this also works with full URLs: `Rails.application.routes.recognize_path 'http://example.com/accounts/1'` – tee May 15 '14 at 19:08
5

There's this method:

>> ActionController::Routing::Routes.recognize_path("/posts/")
=> {:action=>"index", :controller=>"posts"}

If you only have a string with your route (like "posts_path"), then I guess in the context you're using this you should be able to do

ActionController::Routing::Routes.recognize_path(send("posts_path".to_sym))

btw this was educating for me too :)

alex.zherdev
  • 23,914
  • 8
  • 62
  • 56
  • 1
    Thx :) so what is `send(:post_path)`? – fl00r Apr 26 '10 at 16:27
  • it's how you call methods with an arbitrary name in ruby :) in this case, if you have a string like `"posts_path"`, and you want to get the value of `posts_path` method instead, then you just do `send("posts_path")` (you don't even need to convert to symbol). it's a core concept in ruby, you'd better be familiar with that :) – alex.zherdev Apr 26 '10 at 16:34
  • ok, thanks, I've got it. I know how `send` works (like eval in this case). But problem was in console (I've just tried `ActionController::Routing::Routes.recognize_path(send("post_path".to_sym))`) so I've got confused because that failed :) – fl00r Apr 26 '10 at 16:39