Skip to content

Commit

Permalink
Restore to: option with an implicit controller
Browse files Browse the repository at this point in the history
The `:to` option for routes can once again be a Symbol or a String
without a controller if the controller is implicitly provided by a
nesting `controller` or `resources` call.
  • Loading branch information
etiennebarrie committed Apr 9, 2024
1 parent 8ad19d9 commit 1530f70
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
19 changes: 14 additions & 5 deletions actionpack/lib/action_dispatch/routing/mapper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -231,12 +231,21 @@ def normalize_options!(options, path_params, modyoule)
if to.nil?
controller = default_controller
action = default_action
elsif to.is_a?(String) && to.include?("#")
to_endpoint = to.split("#").map!(&:-@)
controller = to_endpoint[0]
action = to_endpoint[1]
else
raise ArgumentError, ":to must respond to `action` or `call`, or it must be a String that includes '#'"
if to.is_a?(String)
controller_or_action, action = to.split("#", 2).map!(&:-@)
if !action || action.empty?
action = controller_or_action
else
controller = controller_or_action
end
elsif to.is_a?(Symbol)
action = to
end
controller ||= default_controller
unless controller
raise ArgumentError, ":to must respond to `action` or `call`, or it must be a String that includes '#', or the controller should be implicit"
end
end

controller = add_controller_module(controller, modyoule)
Expand Down
16 changes: 14 additions & 2 deletions actionpack/test/dispatch/routing_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4037,6 +4037,7 @@ def draw(&block)
routes = ActionDispatch::Routing::RouteSet.new
routes.draw(&block)
@app = self.class.build_app routes
@routes = routes
end

def test_missing_controller
Expand All @@ -4057,6 +4058,17 @@ def test_missing_controller_with_to
assert_match(/:to must respond to/, ex.message)
end

def test_implicit_controller_with_to
draw do
controller :foo do
get "/foo/bar", to: "bar"
get "/foo/baz", to: :baz
end
end
assert_routing "/foo/bar", controller: "foo", action: "bar"
assert_routing "/foo/baz", controller: "foo", action: "baz"
end

def test_to_is_a_symbol
ex = assert_raises(ArgumentError) {
draw do
Expand All @@ -4066,13 +4078,13 @@ def test_to_is_a_symbol
assert_match(/:to must respond to/, ex.message)
end

def test_missing_action_on_hash
def test_missing_action_with_to
ex = assert_raises(ArgumentError) {
draw do
get "/foo/bar", to: "foo#"
end
}
assert_match(/Missing :action/, ex.message)
assert_match(/:to must respond to/, ex.message)
end

def test_valid_controller_options_inside_namespace
Expand Down

0 comments on commit 1530f70

Please sign in to comment.