Look up route from requirements (#51850)
* Lookup route from requirements * Add docs * Strings instead of symbols S * Update actionpack/lib/action_dispatch/routing/route_set.rb Co-authored-by: Rafael Mendonça França <rafael@franca.dev> * Update actionpack/lib/action_dispatch/routing/route_set.rb Co-authored-by: Rafael Mendonça França <rafael@franca.dev> * Update actionpack/lib/action_dispatch/routing/route_set.rb Co-authored-by: Rafael Mendonça França <rafael@franca.dev> * Update actionpack/lib/action_dispatch/routing/route_set.rb Co-authored-by: Rafael Mendonça França <rafael@franca.dev> --------- Co-authored-by: Andy Waite <andyw8@users.noreply.github.com> Co-authored-by: Rafael Mendonça França <rafael@franca.dev>
This commit is contained in:
parent
c906f75282
commit
a8fdfffe18
@ -12,8 +12,25 @@
|
||||
|
||||
module ActionDispatch
|
||||
module Routing
|
||||
# :stopdoc:
|
||||
# The RouteSet contains a collection of Route instances, representing the routes
|
||||
# typically defined in `config/routes.rb`.
|
||||
class RouteSet
|
||||
# Returns a Route matching the given requirements, or `nil` if none are found.
|
||||
#
|
||||
# This is intended for use by tools such as Language Servers.
|
||||
#
|
||||
# Given the routes are defined as:
|
||||
#
|
||||
# resources :posts
|
||||
#
|
||||
# Then the following will return the Route for the `show` action:
|
||||
#
|
||||
# Rails.application.routes.from_requirements(controller: "posts", action: "show")
|
||||
def from_requirements(requirements)
|
||||
routes.find { |route| route.requirements == requirements }
|
||||
end
|
||||
# :stopdoc:
|
||||
|
||||
# Since the router holds references to many parts of the system like engines,
|
||||
# controllers and the application itself, inspecting the route set can actually
|
||||
# be really slow, therefore we default alias inspect to to_s.
|
||||
|
@ -165,6 +165,28 @@ def call(env)
|
||||
assert_equal "/wildcard/a%0Anewline", url_helpers.wildcard_path(wildcard_segment: "a\nnewline")
|
||||
end
|
||||
|
||||
test "find a route for the given requirements" do
|
||||
draw do
|
||||
resources :foo
|
||||
resources :bar
|
||||
end
|
||||
|
||||
route = @set.from_requirements(controller: "bar", action: "index")
|
||||
|
||||
assert_equal "bar_index", route.name
|
||||
end
|
||||
|
||||
test "find a route for the given requirements returns nil for no match" do
|
||||
draw do
|
||||
resources :foo
|
||||
resources :bar
|
||||
end
|
||||
|
||||
route = @set.from_requirements(controller: "baz", action: "index")
|
||||
|
||||
assert_nil route
|
||||
end
|
||||
|
||||
private
|
||||
def draw(&block)
|
||||
@set.draw(&block)
|
||||
|
Loading…
Reference in New Issue
Block a user