dependencies.rb 27.3 KB
Newer Older
J
Jeremy Kemper 已提交
1
require 'set'
J
Jeremy Kemper 已提交
2
require 'thread'
3
require 'concurrent'
4
require 'pathname'
5 6 7
require 'active_support/core_ext/module/aliasing'
require 'active_support/core_ext/module/attribute_accessors'
require 'active_support/core_ext/module/introspection'
Y
Yehuda Katz 已提交
8
require 'active_support/core_ext/module/anonymous'
9
require 'active_support/core_ext/module/qualified_const'
10
require 'active_support/core_ext/object/blank'
11
require 'active_support/core_ext/kernel/reporting'
12 13 14
require 'active_support/core_ext/load_error'
require 'active_support/core_ext/name_error'
require 'active_support/core_ext/string/starts_ends_with'
15
require "active_support/dependencies/interlock"
16
require 'active_support/inflector'
J
Jeremy Kemper 已提交
17

18 19 20 21
module ActiveSupport #:nodoc:
  module Dependencies #:nodoc:
    extend self

22 23 24
    mattr_accessor :interlock
    self.interlock = Interlock.new

25 26 27
    # :doc:

    # Execute the supplied block without interference from any
28
    # concurrent loads.
29 30 31 32 33 34
    def self.run_interlock
      Dependencies.interlock.running { yield }
    end

    # Execute the supplied block while holding an exclusive lock,
    # preventing any other thread from being inside a #run_interlock
35
    # block at the same time.
36 37 38 39
    def self.load_interlock
      Dependencies.interlock.loading { yield }
    end

40 41
    # Execute the supplied block while holding an exclusive lock,
    # preventing any other thread from being inside a #run_interlock
42
    # block at the same time.
43 44 45 46
    def self.unload_interlock
      Dependencies.interlock.unloading { yield }
    end

47 48
    # :nodoc:

49 50 51 52 53 54 55 56 57 58 59 60
    # Should we turn on Ruby warnings on the first load of dependent files?
    mattr_accessor :warnings_on_first_load
    self.warnings_on_first_load = false

    # All files ever loaded.
    mattr_accessor :history
    self.history = Set.new

    # All files currently loaded.
    mattr_accessor :loaded
    self.loaded = Set.new

61 62 63 64
    # Stack of files being loaded.
    mattr_accessor :loading
    self.loading = []

65 66
    # Should we load files or require them?
    mattr_accessor :mechanism
67
    self.mechanism = ENV['NO_RELOAD'] ? :require : :load
68 69 70

    # The set of directories from which we may automatically load files. Files
    # under these directories will be reloaded on each request in development mode,
71 72 73
    # unless the directory also appears in autoload_once_paths.
    mattr_accessor :autoload_paths
    self.autoload_paths = []
74 75

    # The set of directories from which automatically loaded constants are loaded
76 77 78
    # only once. All directories in this set must also be present in +autoload_paths+.
    mattr_accessor :autoload_once_paths
    self.autoload_once_paths = []
79

F
Francesco Rodriguez 已提交
80
    # An array of qualified constant names that have been loaded. Adding a name
81
    # to this array will cause it to be unloaded the next time Dependencies are
F
Francesco Rodriguez 已提交
82
    # cleared.
83 84 85 86 87 88 89 90
    mattr_accessor :autoloaded_constants
    self.autoloaded_constants = []

    # An array of constant names that need to be unloaded on every request. Used
    # to allow arbitrary constants to be marked for unloading.
    mattr_accessor :explicitly_unloadable_constants
    self.explicitly_unloadable_constants = []

F
Francesco Rodriguez 已提交
91 92 93
    # The logger is used for generating information on the action run-time
    # (including benchmarking) if available. Can be set to nil for no logging.
    # Compatible with both Ruby's own Logger and Log4r loggers.
94 95
    mattr_accessor :logger

F
Francesco Rodriguez 已提交
96
    # Set to +true+ to enable logging of const_missing and file loads.
97 98 99
    mattr_accessor :log_activity
    self.log_activity = false

F
Francesco Rodriguez 已提交
100 101 102 103
    # The WatchStack keeps a stack of the modules being watched as files are
    # loaded. If a file in the process of being loaded (parent.rb) triggers the
    # load of another file (child.rb) the stack will ensure that child.rb
    # handles the new constants.
W
wycats 已提交
104 105 106 107 108
    #
    # If child.rb is being autoloaded, its constants will be added to
    # autoloaded_constants. If it was being `require`d, they will be discarded.
    #
    # This is handled by walking back up the watch stack and adding the constants
F
Francesco Rodriguez 已提交
109
    # found by child.rb to the list of original constants in parent.rb.
110 111 112
    class WatchStack
      include Enumerable

W
wycats 已提交
113
      # @watching is a stack of lists of constants being watched. For instance,
F
Francesco Rodriguez 已提交
114 115 116
      # if parent.rb is autoloaded, the stack will look like [[Object]]. If
      # parent.rb then requires namespace/child.rb, the stack will look like
      # [[Object], [Namespace]].
W
wycats 已提交
117

118
      def initialize
W
wycats 已提交
119
        @watching = []
120 121 122 123 124
        @stack = Hash.new { |h,k| h[k] = [] }
      end

      def each(&block)
        @stack.each(&block)
125 126
      end

127 128 129 130
      def watching?
        !@watching.empty?
      end

F
Francesco Rodriguez 已提交
131 132
      # Returns a list of new constants found since the last call to
      # <tt>watch_namespaces</tt>.
W
wycats 已提交
133 134
      def new_constants
        constants = []
135

W
wycats 已提交
136 137
        # Grab the list of namespaces that we're looking for new constants under
        @watching.last.each do |namespace|
138
          # Retrieve the constants that were present under the namespace when watch_namespaces
W
wycats 已提交
139
          # was originally called
140
          original_constants = @stack[namespace].last
141

W
wycats 已提交
142
          mod = Inflector.constantize(namespace) if Dependencies.qualified_const_defined?(namespace)
143 144
          next unless mod.is_a?(Module)

W
wycats 已提交
145
          # Get a list of the constants that were added
146
          new_constants = mod.local_constants - original_constants
W
wycats 已提交
147 148 149 150 151 152

          # self[namespace] returns an Array of the constants that are being evaluated
          # for that namespace. For instance, if parent.rb requires child.rb, the first
          # element of self[Object] will be an Array of the constants that were present
          # before parent.rb was required. The second element will be an Array of the
          # constants that were present before child.rb was required.
153
          @stack[namespace].each do |namespace_constants|
154
            namespace_constants.concat(new_constants)
155
          end
156

W
wycats 已提交
157
          # Normalize the list of new constants, and add them to the list we will return
158
          new_constants.each do |suffix|
159
            constants << ([namespace, suffix] - ["Object"]).join("::".freeze)
160
          end
161 162
        end
        constants
W
wycats 已提交
163
      ensure
164
        # A call to new_constants is always called after a call to watch_namespaces
W
wycats 已提交
165
        pop_modules(@watching.pop)
166 167
      end

F
Francesco Rodriguez 已提交
168 169
      # Add a set of modules to the watch stack, remembering the initial
      # constants.
W
wycats 已提交
170
      def watch_namespaces(namespaces)
171
        @watching << namespaces.map do |namespace|
W
wycats 已提交
172 173
          module_name = Dependencies.to_constant_name(namespace)
          original_constants = Dependencies.qualified_const_defined?(module_name) ?
174
            Inflector.constantize(module_name).local_constants : []
W
wycats 已提交
175

176
          @stack[module_name] << original_constants
177
          module_name
178 179 180
        end
      end

181
      private
W
wycats 已提交
182
      def pop_modules(modules)
183
        modules.each { |mod| @stack[mod].pop }
184 185 186
      end
    end

187 188
    # An internal stack used to record which constants are loaded by any block.
    mattr_accessor :constant_watch_stack
189
    self.constant_watch_stack = WatchStack.new
190

F
Francesco Rodriguez 已提交
191
    # Module includes this module.
192
    module ModuleConstMissing #:nodoc:
193
      def self.append_features(base)
194
        base.class_eval do
195
          # Emulate #exclude via an ivar
196
          return if defined?(@_const_missing) && @_const_missing
197
          @_const_missing = instance_method(:const_missing)
198
          remove_method(:const_missing)
199
        end
200
        super
201
      end
202

203
      def self.exclude_from(base)
204
        base.class_eval do
205 206
          define_method :const_missing, @_const_missing
          @_const_missing = nil
207 208 209
        end
      end

210
      def const_missing(const_name)
211
        from_mod = anonymous? ? guess_for_anonymous(const_name) : self
212
        Dependencies.load_missing_constant(from_mod, const_name)
213 214
      end

215 216 217 218 219
      # We assume that the name of the module reflects the nesting
      # (unless it can be proven that is not the case) and the path to the file
      # that defines the constant. Anonymous modules cannot follow these
      # conventions and therefore we assume that the user wants to refer to a
      # top-level constant.
220 221
      def guess_for_anonymous(const_name)
        if Object.const_defined?(const_name)
222
          raise NameError.new "#{const_name} cannot be autoloaded from an anonymous class or module", const_name
223 224 225 226 227
        else
          Object
        end
      end

228 229
      def unloadable(const_desc = self)
        super(const_desc)
230 231 232
      end
    end

F
Francesco Rodriguez 已提交
233
    # Object includes this module.
234
    module Loadable #:nodoc:
235
      def self.exclude_from(base)
236 237 238 239
        base.class_eval do
          define_method(:load, Kernel.instance_method(:load))
          private :load
        end
240 241 242 243 244 245
      end

      def require_or_load(file_name)
        Dependencies.require_or_load(file_name)
      end

246 247 248 249 250 251 252 253 254
      # Interprets a file using <tt>mechanism</tt> and marks its defined
      # constants as autoloaded. <tt>file_name</tt> can be either a string or
      # respond to <tt>to_path</tt>.
      #
      # Use this method in code that absolutely needs a certain constant to be
      # defined at that point. A typical use case is to make constant name
      # resolution deterministic for constants with the same relative name in
      # different namespaces whose evaluation would depend on load order
      # otherwise.
255
      def require_dependency(file_name, message = "No such file to load -- %s")
256
        file_name = file_name.to_path if file_name.respond_to?(:to_path)
Y
Right.  
Yehuda Katz 已提交
257
        unless file_name.is_a?(String)
258
          raise ArgumentError, "the file name must either be a String or implement #to_path -- you passed #{file_name.inspect}"
Y
Right.  
Yehuda Katz 已提交
259 260
        end

261
        Dependencies.depend_on(file_name, message)
262 263
      end

264
      def load_dependency(file)
265 266 267 268
        if Dependencies.load? && ActiveSupport::Dependencies.constant_watch_stack.watching?
          Dependencies.new_constants_in(Object) { yield }
        else
          yield
269
        end
270
      rescue Exception => exception  # errors from loading file
271
        exception.blame_file! file if exception.respond_to? :blame_file!
272 273 274
        raise
      end

F
Francesco Rodriguez 已提交
275 276
      # Mark the given constant as unloadable. Unloadable constants are removed
      # each time dependencies are cleared.
277 278 279
      #
      # Note that marking a constant for unloading need only be done once. Setup
      # or init scripts may list each unloadable constant that may need unloading;
F
Francesco Rodriguez 已提交
280 281
      # each constant will be removed for every subsequent clear, as opposed to
      # for the first clear.
282 283 284 285
      #
      # The provided constant descriptor may be a (non-anonymous) module or class,
      # or a qualified constant name as a string or symbol.
      #
F
Francesco Rodriguez 已提交
286 287
      # Returns +true+ if the constant was not previously marked for unloading,
      # +false+ otherwise.
288 289 290
      def unloadable(const_desc)
        Dependencies.mark_for_unload const_desc
      end
291 292 293 294 295 296 297 298 299 300 301 302 303 304

      private

      def load(file, wrap = false)
        result = false
        load_dependency(file) { result = super }
        result
      end

      def require(file)
        result = false
        load_dependency(file) { result = super }
        result
      end
305 306
    end

F
Francesco Rodriguez 已提交
307
    # Exception file-blaming.
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
    module Blamable #:nodoc:
      def blame_file!(file)
        (@blamed_files ||= []).unshift file
      end

      def blamed_files
        @blamed_files ||= []
      end

      def describe_blame
        return nil if blamed_files.empty?
        "This error occurred while loading the following files:\n   #{blamed_files.join "\n   "}"
      end

      def copy_blame!(exc)
        @blamed_files = exc.blamed_files.clone
        self
      end
    end

328
    def hook!
329 330 331
      Object.class_eval { include Loadable }
      Module.class_eval { include ModuleConstMissing }
      Exception.class_eval { include Blamable }
332 333 334
    end

    def unhook!
335 336
      ModuleConstMissing.exclude_from(Module)
      Loadable.exclude_from(Object)
337 338
    end

339 340 341
    def load?
      mechanism == :load
    end
342

343
    def depend_on(file_name, message = "No such file to load -- %s.rb")
344 345 346
      path = search_for_file(file_name)
      require_or_load(path || file_name)
    rescue LoadError => load_error
347
      if file_name = load_error.message[/ -- (.*?)(\.rb)?$/, 1]
348 349
        load_error.message.replace(message % file_name)
        load_error.copy_blame!(load_error)
350
      end
351
      raise
352
    end
353

354 355
    def clear
      log_call
356
      Dependencies.unload_interlock do
357 358 359 360
        loaded.clear
        loading.clear
        remove_unloadable_constants!
      end
361
    end
362

363 364
    def require_or_load(file_name, const_path = nil)
      log_call file_name, const_path
X
Xavier Noria 已提交
365
      file_name = $` if file_name =~ /\.rb\z/
366 367
      expanded = File.expand_path(file_name)
      return if loaded.include?(expanded)
368

369
      Dependencies.load_interlock do
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
        # Maybe it got loaded while we were waiting for our lock:
        return if loaded.include?(expanded)

        # Record that we've seen this file *before* loading it to avoid an
        # infinite loop with mutual dependencies.
        loaded << expanded
        loading << expanded

        begin
          if load?
            log "loading #{file_name}"

            # Enable warnings if this file has not been loaded before and
            # warnings_on_first_load is set.
            load_args = ["#{file_name}.rb"]
            load_args << const_path unless const_path.nil?

            if !warnings_on_first_load or history.include?(expanded)
              result = load_file(*load_args)
            else
              enable_warnings { result = load_file(*load_args) }
            end
392
          else
393 394
            log "requiring #{file_name}"
            result = require file_name
395
          end
396 397 398 399 400
        rescue Exception
          loaded.delete expanded
          raise
        ensure
          loading.pop
401
        end
402

403 404 405 406
        # Record history *after* loading so first load gets warnings.
        history << expanded
        result
      end
407
    end
408

409
    # Is the provided constant path defined?
J
José Valim 已提交
410
    def qualified_const_defined?(path)
411
      Object.const_defined?(path, false)
412
    end
413

F
Francesco Rodriguez 已提交
414 415
    # Given +path+, a filesystem path to a ruby file, return an array of
    # constant paths which would cause Dependencies to attempt to load this
416
    # file.
417
    def loadable_constants_for_path(path, bases = autoload_paths)
X
Xavier Noria 已提交
418
      path = $` if path =~ /\.rb\z/
419 420 421 422 423
      expanded_path = File.expand_path(path)
      paths = []

      bases.each do |root|
        expanded_root = File.expand_path(root)
424
        next unless expanded_path.start_with?(expanded_root)
425

426 427
        root_size = expanded_root.size
        next if expanded_path[root_size] != ?/.freeze
428

429 430
        nesting = expanded_path[(root_size + 1)..-1]
        paths << nesting.camelize unless nesting.blank?
431 432 433 434
      end

      paths.uniq!
      paths
435
    end
436

437
    # Search for a file in autoload_paths matching the provided suffix.
438
    def search_for_file(path_suffix)
439
      path_suffix = path_suffix.sub(/(\.rb)?$/, ".rb".freeze)
440

441
      autoload_paths.each do |root|
442 443 444 445
        path = File.join(root, path_suffix)
        return path if File.file? path
      end
      nil # Gee, I sure wish we had first_match ;-)
446
    end
447

448
    # Does the provided path_suffix correspond to an autoloadable module?
F
Francesco Rodriguez 已提交
449 450
    # Instead of returning a boolean, the autoload base for this module is
    # returned.
451
    def autoloadable_module?(path_suffix)
452
      autoload_paths.each do |load_path|
453 454 455
        return load_path if File.directory? File.join(load_path, path_suffix)
      end
      nil
456
    end
457

458
    def load_once_path?(path)
459
      # to_s works around a ruby issue where String#starts_with?(Pathname)
460
      # will raise a TypeError: no implicit conversion of Pathname into String
461
      autoload_once_paths.any? { |base| path.starts_with? base.to_s }
462
    end
463

464
    # Attempt to autoload the provided module name by searching for a directory
F
Francesco Rodriguez 已提交
465 466
    # matching the expected path suffix. If found, the module is created and
    # assigned to +into+'s constants with the name +const_name+. Provided that
467
    # the directory was loaded from a reloadable base path, it is added to the
F
Francesco Rodriguez 已提交
468
    # set of constants that are to be unloaded.
469 470 471 472
    def autoload_module!(into, const_name, qualified_name, path_suffix)
      return nil unless base_path = autoloadable_module?(path_suffix)
      mod = Module.new
      into.const_set const_name, mod
473
      autoloaded_constants << qualified_name unless autoload_once_paths.include?(base_path)
474
      mod
475
    end
476

477 478 479 480 481
    # Load the file at the provided path. +const_paths+ is a set of qualified
    # constant names. When loading the file, Dependencies will watch for the
    # addition of these constants. Each that is defined will be marked as
    # autoloaded, and will be removed when Dependencies.clear is next called.
    #
F
Francesco Rodriguez 已提交
482 483
    # If the second parameter is left off, then Dependencies will construct a
    # set of names that the file at +path+ may define. See
484 485 486 487
    # +loadable_constants_for_path+ for more details.
    def load_file(path, const_paths = loadable_constants_for_path(path))
      log_call path, const_paths
      const_paths = [const_paths].compact unless const_paths.is_a? Array
488
      parent_paths = const_paths.collect { |const_path| const_path[/.*(?=::)/] || ::Object }
489 490 491

      result = nil
      newly_defined_paths = new_constants_in(*parent_paths) do
492
        result = Kernel.load path
493
      end
J
Jeremy Kemper 已提交
494

495 496 497
      autoloaded_constants.concat newly_defined_paths unless load_once_path?(path)
      autoloaded_constants.uniq!
      log "loading #{path} defined #{newly_defined_paths * ', '}" unless newly_defined_paths.empty?
498
      result
499
    end
J
Jeremy Kemper 已提交
500

F
Francesco Rodriguez 已提交
501
    # Returns the constant path for the provided parent and constant name.
502 503
    def qualified_name_for(mod, name)
      mod_name = to_constant_name mod
504
      mod_name == "Object" ? name.to_s : "#{mod_name}::#{name}"
505
    end
506

507
    # Load the constant named +const_name+ which is missing from +from_mod+. If
F
Francesco Rodriguez 已提交
508 509
    # it is not possible to load the constant into from_mod, try its parent
    # module using +const_missing+.
510 511
    def load_missing_constant(from_mod, const_name)
      log_call from_mod, const_name
512

513
      unless qualified_const_defined?(from_mod.name) && Inflector.constantize(from_mod.name).equal?(from_mod)
514 515 516 517 518
        raise ArgumentError, "A copy of #{from_mod} has been removed from the module tree but is still active!"
      end

      qualified_name = qualified_name_for from_mod, const_name
      path_suffix = qualified_name.underscore
519

520
      file_path = search_for_file(path_suffix)
521

522 523
      if file_path
        expanded = File.expand_path(file_path)
524
        expanded.sub!(/\.rb\z/, ''.freeze)
525

526
        if loading.include?(expanded)
527 528
          raise "Circular dependency detected while autoloading constant #{qualified_name}"
        else
529
          require_or_load(expanded, qualified_name)
530
          raise LoadError, "Unable to autoload constant #{qualified_name}, expected #{file_path} to define it" unless from_mod.const_defined?(const_name, false)
531 532
          return from_mod.const_get(const_name)
        end
533 534 535
      elsif mod = autoload_module!(from_mod, const_name, qualified_name, path_suffix)
        return mod
      elsif (parent = from_mod.parent) && parent != from_mod &&
536
            ! from_mod.parents.any? { |p| p.const_defined?(const_name, false) }
537 538 539 540 541
        # If our parents do not have a constant named +const_name+ then we are free
        # to attempt to load upwards. If they do have such a constant, then this
        # const_missing must be due to from_mod::const_name, which should not
        # return constants from from_mod's parents.
        begin
X
Xavier Noria 已提交
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
          # Since Ruby does not pass the nesting at the point the unknown
          # constant triggered the callback we cannot fully emulate constant
          # name lookup and need to make a trade-off: we are going to assume
          # that the nesting in the body of Foo::Bar is [Foo::Bar, Foo] even
          # though it might not be. Counterexamples are
          #
          #   class Foo::Bar
          #     Module.nesting # => [Foo::Bar]
          #   end
          #
          # or
          #
          #   module M::N
          #     module S::T
          #       Module.nesting # => [S::T, M::N]
          #     end
          #   end
          #
          # for example.
561 562 563 564
          return parent.const_missing(const_name)
        rescue NameError => e
          raise unless e.missing_name? qualified_name_for(parent, const_name)
        end
565
      end
566

567
      name_error = NameError.new("uninitialized constant #{qualified_name}", const_name)
568 569
      name_error.set_backtrace(caller.reject {|l| l.starts_with? __FILE__ })
      raise name_error
570
    end
571

572
    # Remove the constants that have been autoloaded, and those that have been
573 574 575 576
    # marked for unloading. Before each constant is removed a callback is sent
    # to its class/module if it implements +before_remove_const+.
    #
    # The callback implementation should be restricted to cleaning up caches, etc.
R
R.T. Lechow 已提交
577
    # as the environment will be in an inconsistent state, e.g. other constants
578
    # may have already been unloaded and not accessible.
579 580 581
    def remove_unloadable_constants!
      autoloaded_constants.each { |const| remove_constant const }
      autoloaded_constants.clear
582
      Reference.clear!
583 584
      explicitly_unloadable_constants.each { |const| remove_constant const }
    end
585

586 587
    class ClassCache
      def initialize
588
        @store = Concurrent::Map.new
589 590 591 592 593 594 595 596 597
      end

      def empty?
        @store.empty?
      end

      def key?(key)
        @store.key?(key)
      end
598

599 600 601
      def get(key)
        key = key.name if key.respond_to?(:name)
        @store[key] ||= Inflector.constantize(key)
602
      end
603
      alias :[] :get
604

605
      def safe_get(key)
606
        key = key.name if key.respond_to?(:name)
607
        @store[key] ||= Inflector.safe_constantize(key)
W
wycats 已提交
608 609
      end

610 611 612 613
      def store(klass)
        return self unless klass.respond_to?(:name)
        raise(ArgumentError, 'anonymous classes cannot be cached') if klass.name.empty?
        @store[klass.name] = klass
614 615 616
        self
      end

617 618
      def clear!
        @store.clear
W
wycats 已提交
619 620 621
      end
    end

622 623
    Reference = ClassCache.new

624 625 626 627
    # Store a reference to a class +klass+.
    def reference(klass)
      Reference.store klass
    end
628

629
    # Get the reference for class named +name+.
630
    # Raises an exception if referenced class does not exist.
631
    def constantize(name)
632
      Reference.get(name)
W
wycats 已提交
633 634
    end

635
    # Get the reference for class named +name+ if one exists.
F
Francesco Rodriguez 已提交
636
    # Otherwise returns +nil+.
637 638 639 640
    def safe_constantize(name)
      Reference.safe_get(name)
    end

641 642
    # Determine if the given constant has been automatically loaded.
    def autoloaded?(desc)
643
      return false if desc.is_a?(Module) && desc.anonymous?
644
      name = to_constant_name desc
645
      return false unless qualified_const_defined?(name)
646 647
      return autoloaded_constants.include?(name)
    end
648

649 650
    # Will the provided constant descriptor be unloaded?
    def will_unload?(const_desc)
651
      autoloaded?(const_desc) ||
652 653
        explicitly_unloadable_constants.include?(to_constant_name(const_desc))
    end
654

655 656 657 658 659
    # Mark the provided constant name for unloading. This constant will be
    # unloaded on each request, not just the next one.
    def mark_for_unload(const_desc)
      name = to_constant_name const_desc
      if explicitly_unloadable_constants.include? name
660
        false
661 662
      else
        explicitly_unloadable_constants << name
663
        true
664
      end
665
    end
666

667 668 669 670 671 672 673 674 675 676
    # Run the provided block and detect the new constants that were loaded during
    # its execution. Constants may only be regarded as 'new' once -- so if the
    # block calls +new_constants_in+ again, then the constants defined within the
    # inner call will not be reported in this one.
    #
    # If the provided block does not run to completion, and instead raises an
    # exception, any new constants are regarded as being only partially defined
    # and will be removed immediately.
    def new_constants_in(*descs)
      log_call(*descs)
677

W
wycats 已提交
678
      constant_watch_stack.watch_namespaces(descs)
679
      aborting = true
W
wycats 已提交
680

681 682 683 684
      begin
        yield # Now yield to the code that is to define new constants.
        aborting = false
      ensure
W
wycats 已提交
685
        new_constants = constant_watch_stack.new_constants
686 687

        log "New constants: #{new_constants * ', '}"
688
        return new_constants unless aborting
689

690
        log "Error during loading, removing partially loaded constants "
691
        new_constants.each { |c| remove_constant(c) }.clear
692
      end
693

694
      []
695
    end
696

697 698 699
    # Convert the provided const desc to a qualified constant name (as a string).
    # A module, class, symbol, or string may be provided.
    def to_constant_name(desc) #:nodoc:
S
Santiago Pastorino 已提交
700
      case desc
701
        when String then desc.sub(/^::/, '')
702 703
        when Symbol then desc.to_s
        when Module
704
          desc.name ||
705
            raise(ArgumentError, "Anonymous modules have no name to be referenced by")
706
        else raise TypeError, "Not a valid constant descriptor: #{desc.inspect}"
707 708
      end
    end
709

710
    def remove_constant(const) #:nodoc:
711 712 713 714
      # Normalize ::Foo, ::Object::Foo, Object::Foo, Object::Object::Foo, etc. as Foo.
      normalized = const.to_s.sub(/\A::/, '')
      normalized.sub!(/\A(Object::)+/, '')

715 716
      constants = normalized.split('::')
      to_remove = constants.pop
717

718 719 720 721 722 723 724 725
      # Remove the file path from the loaded list.
      file_path = search_for_file(const.underscore)
      if file_path
        expanded = File.expand_path(file_path)
        expanded.sub!(/\.rb\z/, '')
        self.loaded.delete(expanded)
      end

726 727 728 729
      if constants.empty?
        parent = Object
      else
        # This method is robust to non-reachable constants.
730
        #
731 732 733 734 735 736 737 738 739
        # Non-reachable constants may be passed if some of the parents were
        # autoloaded and already removed. It is easier to do a sanity check
        # here than require the caller to be clever. We check the parent
        # rather than the very const argument because we do not want to
        # trigger Kernel#autoloads, see the comment below.
        parent_name = constants.join('::')
        return unless qualified_const_defined?(parent_name)
        parent = constantize(parent_name)
      end
J
Jeremy Kemper 已提交
740

741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
      log "removing constant #{const}"

      # In an autoloaded user.rb like this
      #
      #   autoload :Foo, 'foo'
      #
      #   class User < ActiveRecord::Base
      #   end
      #
      # we correctly register "Foo" as being autoloaded. But if the app does
      # not use the "Foo" constant we need to be careful not to trigger
      # loading "foo.rb" ourselves. While #const_defined? and #const_get? do
      # require the file, #autoload? and #remove_const don't.
      #
      # We are going to remove the constant nonetheless ---which exists as
      # far as Ruby is concerned--- because if the user removes the macro
      # call from a class or module that were not autoloaded, as in the
      # example above with Object, accessing to that constant must err.
      unless parent.autoload?(to_remove)
760
        begin
761
          constantized = parent.const_get(to_remove, false)
762 763
        rescue NameError
          log "the constant #{const} is not reachable anymore, skipping"
764 765 766
          return
        else
          constantized.before_remove_const if constantized.respond_to?(:before_remove_const)
767 768
        end
      end
769 770 771 772 773 774

      begin
        parent.instance_eval { remove_const to_remove }
      rescue NameError
        log "the constant #{const} is not reachable anymore, skipping"
      end
775
    end
J
Jeremy Kemper 已提交
776

777 778
    protected
      def log_call(*args)
779
        if log_activity?
780
          arg_str = args.collect(&:inspect) * ', '
781 782 783 784 785
          /in `([a-z_\?\!]+)'/ =~ caller(1).first
          selector = $1 || '<unknown>'
          log "called #{selector}(#{arg_str})"
        end
      end
786

787
      def log(msg)
788 789 790 791 792
        logger.debug "Dependencies: #{msg}" if log_activity?
      end

      def log_activity?
        logger && log_activity
793
      end
794
  end
795 796
end

797
ActiveSupport::Dependencies.hook!