aboutsummaryrefslogtreecommitdiffstats
path: root/railties/lib/rails/command/behavior.rb
blob: 7fb2a99e67afe14265ccfafafb2c7e31778f7e6f (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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# frozen_string_literal: true

require "active_support"

module Rails
  module Command
    module Behavior #:nodoc:
      extend ActiveSupport::Concern

      class_methods do
        # Remove the color from output.
        def no_color!
          Thor::Base.shell = Thor::Shell::Basic
        end

        # Track all command subclasses.
        def subclasses
          @subclasses ||= []
        end

        private
          # Prints a list of generators.
          def print_list(base, namespaces)
            return if namespaces.empty?
            puts "#{base.camelize}:"

            namespaces.each do |namespace|
              puts("  #{namespace}")
            end

            puts
          end

          # Receives namespaces in an array and tries to find matching generators
          # in the load path.
          def lookup(namespaces)
            paths = namespaces_to_paths(namespaces)

            paths.each do |raw_path|
              lookup_paths.each do |base|
                path = "#{base}/#{raw_path}_#{command_type}"

                begin
                  require path
                  return
                rescue LoadError => e
                  raise unless e.message =~ /#{Regexp.escape(path)}$/
                rescue Exception => e
                  warn "[WARNING] Could not load #{command_type} #{path.inspect}. Error: #{e.message}.\n#{e.backtrace.join("\n")}"
                end
              end
            end
          end

          # This will try to load any command in the load path to show in help.
          def lookup!
            $LOAD_PATH.each do |base|
              Dir[File.join(base, *file_lookup_paths)].each do |path|
                path = path.sub("#{base}/", "")
                require path
              rescue Exception
                # No problem
              end
            end
          end

          # Convert namespaces to paths by replacing ":" for "/" and adding
          # an extra lookup. For example, "rails:model" should be searched
          # in both: "rails/model/model_generator" and "rails/model_generator".
          def namespaces_to_paths(namespaces)
            paths = []
            namespaces.each do |namespace|
              pieces = namespace.split(":")
              path = pieces.join("/")
              paths << "#{path}/#{pieces.last}"
              paths << path
            end
            paths.uniq!
            paths
          end
      end
    end
  end
end