Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge pull request #11544 from prathamesh-sonpatki/namespaced_routes_…

…test

Generate namespaced routes correctly for generators. Fix for #11532
  • Loading branch information...
commit 271d622a4ddc35c21bc8b853e4e2901a9ede43bd 2 parents 77ba336 + 53c5794
@senny senny authored
View
18 railties/CHANGELOG.md
@@ -1,3 +1,21 @@
+* Generate nested route for namespaced controller generated using
+ `rails g controller`.
+ Fixes #11532.
+
+ Example:
+
+ rails g controller admin/dashboard index
+
+ # Before:
+ get "dashboard/index"
+
+ # After:
+ namespace :admin do
+ get "dashboard/index"
+ end
+
+ *Prathamesh Sonpatki*
+
* Fix the event name of action_dispatch requests.
*Rafael Mendonça França*
View
36 railties/lib/rails/generators/rails/controller/controller_generator.rb
@@ -10,11 +10,45 @@ def create_controller_files
def add_routes
actions.reverse.each do |action|
- route %{get "#{file_name}/#{action}"}
+ route generate_routing_code(action)
end
end
hook_for :template_engine, :test_framework, :helper, :assets
+
+ private
+
+ # This method creates nested route entry for namespaced resources.
+ # For eg. rails g controller foo/bar/baz index
+ # Will generate -
+ # namespace :foo do
+ # namespace :bar do
+ # get "baz/index"
+ # end
+ # end
+ def generate_routing_code(action)
+ depth = class_path.length
+ # Create 'namespace' ladder
+ # namespace :foo do
+ # namespace :bar do
+ namespace_ladder = class_path.each_with_index.map do |ns, i|
+ %{#{" " * i * 2}namespace :#{ns} do\n }
+ end.join
+
+ # Create route
+ # get "baz/index"
+ route = %{#{" " * depth * 2}get "#{file_name}/#{action}"\n}
+
+ # Create `end` ladder
+ # end
+ # end
+ end_ladder = (1..depth).reverse_each.map do |i|
+ "#{" " * i * 2}end\n"
+ end.join
+
+ # Combine the 3 parts to generate complete route entry
+ namespace_ladder + route + end_ladder
+ end
end
end
end
View
5 railties/test/generators/controller_generator_test.rb
@@ -82,4 +82,9 @@ def test_actions_are_turned_into_methods
assert_instance_method :bar, controller
end
end
+
+ def test_namespaced_routes_are_created_in_routes
+ run_generator ["admin/dashboard", "index"]
+ assert_file "config/routes.rb", /namespace :admin do\n\s+get "dashboard\/index"\n/
+ end
end
Please sign in to comment.
Something went wrong with that request. Please try again.