aboutsummaryrefslogtreecommitdiffstats
path: root/railties/lib/rails/generators/app_name.rb
blob: c4f71694d88033738f87a1d87cbad3804e3eba43 (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
49
50
# frozen_string_literal: true

module Rails
  module Generators
    module AppName # :nodoc:
      RESERVED_NAMES = %w(application destroy plugin runner test)

      private
        def app_name
          @app_name ||= original_app_name.tr("-", "_")
        end

        def original_app_name
          @original_app_name ||= (defined_app_const_base? ? defined_app_name : File.basename(destination_root)).tr('\\', "").tr(". ", "_")
        end

        def defined_app_name
          defined_app_const_base.underscore
        end

        def defined_app_const_base
          Rails.respond_to?(:application) && defined?(Rails::Application) &&
            Rails.application.is_a?(Rails::Application) && Rails.application.class.name.chomp("::Application")
        end

        alias :defined_app_const_base? :defined_app_const_base

        def app_const_base
          @app_const_base ||= defined_app_const_base || app_name.gsub(/\W/, "_").squeeze("_").camelize
        end
        alias :camelized :app_const_base

        def app_const
          @app_const ||= "#{app_const_base}::Application"
        end

        def valid_const?
          if /^\d/.match?(app_const)
            raise Error, "Invalid application name #{original_app_name}. Please give a name which does not start with numbers."
          elsif RESERVED_NAMES.include?(original_app_name)
            raise Error, "Invalid application name #{original_app_name}. Please give a " \
                         "name which does not match one of the reserved rails " \
                         "words: #{RESERVED_NAMES.join(", ")}"
          elsif Object.const_defined?(app_const_base)
            raise Error, "Invalid application name #{original_app_name}, constant #{app_const_base} is already in use. Please choose another application name."
          end
        end
    end
  end
end