Skip to content

Commit a8fdfff

Browse files
andyw8rafaelfranca
andauthored
Look up route from requirements (rails#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 <[email protected]> * Update actionpack/lib/action_dispatch/routing/route_set.rb Co-authored-by: Rafael Mendonça França <[email protected]> * Update actionpack/lib/action_dispatch/routing/route_set.rb Co-authored-by: Rafael Mendonça França <[email protected]> * Update actionpack/lib/action_dispatch/routing/route_set.rb Co-authored-by: Rafael Mendonça França <[email protected]> --------- Co-authored-by: Andy Waite <[email protected]> Co-authored-by: Rafael Mendonça França <[email protected]>
1 parent c906f75 commit a8fdfff

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

actionpack/lib/action_dispatch/routing/route_set.rb

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,25 @@
1212

1313
module ActionDispatch
1414
module Routing
15-
# :stopdoc:
15+
# The RouteSet contains a collection of Route instances, representing the routes
16+
# typically defined in `config/routes.rb`.
1617
class RouteSet
18+
# Returns a Route matching the given requirements, or `nil` if none are found.
19+
#
20+
# This is intended for use by tools such as Language Servers.
21+
#
22+
# Given the routes are defined as:
23+
#
24+
# resources :posts
25+
#
26+
# Then the following will return the Route for the `show` action:
27+
#
28+
# Rails.application.routes.from_requirements(controller: "posts", action: "show")
29+
def from_requirements(requirements)
30+
routes.find { |route| route.requirements == requirements }
31+
end
32+
# :stopdoc:
33+
1734
# Since the router holds references to many parts of the system like engines,
1835
# controllers and the application itself, inspecting the route set can actually
1936
# be really slow, therefore we default alias inspect to to_s.

actionpack/test/dispatch/routing/route_set_test.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,28 @@ def call(env)
165165
assert_equal "/wildcard/a%0Anewline", url_helpers.wildcard_path(wildcard_segment: "a\nnewline")
166166
end
167167

168+
test "find a route for the given requirements" do
169+
draw do
170+
resources :foo
171+
resources :bar
172+
end
173+
174+
route = @set.from_requirements(controller: "bar", action: "index")
175+
176+
assert_equal "bar_index", route.name
177+
end
178+
179+
test "find a route for the given requirements returns nil for no match" do
180+
draw do
181+
resources :foo
182+
resources :bar
183+
end
184+
185+
route = @set.from_requirements(controller: "baz", action: "index")
186+
187+
assert_nil route
188+
end
189+
168190
private
169191
def draw(&block)
170192
@set.draw(&block)

0 commit comments

Comments
 (0)