# in a controller or a template
<% request.routes.router.recognize(request) do |route, _params| %>
<%= route.path.spec.to_s %> # => /users/:id(.:format)
<% end %>
# in a console
>> Rails.application.routes.router.recognize(
ActionDispatch::Request.new(Rack::MockRequest.env_for("/users/1/edit", method: :get))
) {}.map {|_,_,route| route.path.spec.to_s }
=> ["/users/:id/edit(.:format)"]
>> Rails.application.routes.routes.simulator.memos("/users/1/edit").first.ast.to_s
=> "/users/:id/edit(.:format)"
# NOTE: if route doesn't match it will `yield` and raise
# no block given (yield) (LocalJumpError)
# just rescue or give it an empty block.
1条答案
按热度按时间bzzcjhmw1#
我所知道的唯一一个可以获得这些信息的地方是
bin/rails routes
。它使用inspector来收集所有信息:也许你还能在那里找到别的东西。但我提取了你所要求的主要部分:
route
这里是ActionDispatch::Journey::Route
示例,它有关于路由的所有信息。我甚至不知道这是什么,但它确实做到了: