Skip to content

Commit

Permalink
Look up route from requirements (#51850)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
3 people committed May 23, 2024
1 parent 8f46ce9 commit e8520fa
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
19 changes: 18 additions & 1 deletion actionpack/lib/action_dispatch/routing/route_set.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
22 changes: 22 additions & 0 deletions actionpack/test/dispatch/routing/route_set_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit e8520fa

Please sign in to comment.