aboutsummaryrefslogtreecommitdiffstats
path: root/railties/lib/rails/generators/rails/resource_route/resource_route_generator.rb
blob: 9a92991efed462793cad6a050f35ab87beed90bd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# frozen_string_literal: true

module Rails
  module Generators
    class ResourceRouteGenerator < NamedBase # :nodoc:
      # Properly nests namespaces passed into a generator
      #
      #   $ rails generate resource admin/users/products
      #
      # should give you
      #
      #   namespace :admin do
      #     namespace :users do
      #       resources :products
      #     end
      #   end
      def add_resource_route
        return if options[:actions].present?

        depth = 0
        lines = []

        # Create 'namespace' ladder
        # namespace :foo do
        #   namespace :bar do
        regular_class_path.each do |ns|
          lines << indent("namespace :#{ns} do\n", depth * 2)
          depth += 1
        end

        # inserts the primary resource
        # Create route
        #     resources 'products'
        lines << indent(%{resources :#{file_name.pluralize}\n}, depth * 2)

        # Create `end` ladder
        #   end
        # end
        until depth.zero?
          depth -= 1
          lines << indent("end\n", depth * 2)
        end

        route lines.join
      end
    end
  end
end