Module: ActiveSupport::Dependencies

Extended by:
Dependencies
Included in:
Dependencies
Defined in:
lib/active_support/dependencies.rb,
lib/active_support/dependencies/interlock.rb,
lib/active_support/dependencies/zeitwerk_integration.rb

Overview

:nodoc:

Defined Under Namespace

Modules: Blamable, Loadable, ModuleConstMissing, ZeitwerkIntegration Classes: ClassCache, Interlock, WatchStack

Constant Summary collapse

Reference =
ClassCache.new

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.load_interlockObject

Execute the supplied block while holding an exclusive lock, preventing any other thread from being inside a #run_interlock block at the same time.


38
39
40
# File 'lib/active_support/dependencies.rb', line 38

def self.load_interlock
  Dependencies.interlock.loading { yield }
end

.run_interlockObject

Execute the supplied block without interference from any concurrent loads.


31
32
33
# File 'lib/active_support/dependencies.rb', line 31

def self.run_interlock
  Dependencies.interlock.running { yield }
end

.unload_interlockObject

Execute the supplied block while holding an exclusive lock, preventing any other thread from being inside a #run_interlock block at the same time.


45
46
47
# File 'lib/active_support/dependencies.rb', line 45

def self.unload_interlock
  Dependencies.interlock.unloading { yield }
end

Instance Method Details

#autoload_module!(into, const_name, qualified_name, path_suffix) ⇒ Object

Attempt to autoload the provided module name by searching for a directory matching the expected path suffix. If found, the module is created and assigned to into's constants with the name const_name. Provided that the directory was loaded from a reloadable base path, it is added to the set of constants that are to be unloaded.


499
500
501
502
503
504
505
506
507
# File 'lib/active_support/dependencies.rb', line 499

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
  log("constant #{qualified_name} autoloaded (module autovivified from #{File.join(base_path, path_suffix)})")
  autoloaded_constants << qualified_name unless autoload_once_paths.include?(base_path)
  autoloaded_constants.uniq!
  mod
end

#autoloadable_module?(path_suffix) ⇒ Boolean

Does the provided path_suffix correspond to an autoloadable module? Instead of returning a boolean, the autoload base for this module is returned.

Returns:

  • (Boolean)

481
482
483
484
485
486
# File 'lib/active_support/dependencies.rb', line 481

def autoloadable_module?(path_suffix)
  autoload_paths.each do |load_path|
    return load_path if File.directory? File.join(load_path, path_suffix)
  end
  nil
end

#autoloaded?(desc) ⇒ Boolean

Determine if the given constant has been automatically loaded.

Returns:

  • (Boolean)

677
678
679
680
681
682
# File 'lib/active_support/dependencies.rb', line 677

def autoloaded?(desc)
  return false if desc.is_a?(Module) && real_mod_name(desc).nil?
  name = to_constant_name desc
  return false unless qualified_const_defined?(name)
  autoloaded_constants.include?(name)
end

#clearObject


389
390
391
392
393
394
395
# File 'lib/active_support/dependencies.rb', line 389

def clear
  Dependencies.unload_interlock do
    loaded.clear
    loading.clear
    remove_unloadable_constants!
  end
end

#constantize(name) ⇒ Object

Get the reference for class named name. Raises an exception if referenced class does not exist.


666
667
668
# File 'lib/active_support/dependencies.rb', line 666

def constantize(name)
  Reference.get(name)
end

#depend_on(file_name, message = "No such file to load -- %s.rb") ⇒ Object


373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'lib/active_support/dependencies.rb', line 373

def depend_on(file_name, message = "No such file to load -- %s.rb")
  path = search_for_file(file_name)
  require_or_load(path || file_name)
rescue LoadError => load_error
  if file_name = load_error.message[/ -- (.*?)(\.rb)?$/, 1]
    load_error_message = if load_error.respond_to?(:original_message)
      load_error.original_message
    else
      load_error.message
    end
    load_error_message.replace(message % file_name)
    load_error.copy_blame!(load_error)
  end
  raise
end

#hook!Object


358
359
360
361
362
# File 'lib/active_support/dependencies.rb', line 358

def hook!
  Loadable.include_into(Object)
  ModuleConstMissing.include_into(Module)
  Exception.include(Blamable)
end

#load?Boolean

Returns:

  • (Boolean)

369
370
371
# File 'lib/active_support/dependencies.rb', line 369

def load?
  mechanism == :load
end

#load_file(path, const_paths = loadable_constants_for_path(path)) ⇒ Object

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.

If the second parameter is left off, then Dependencies will construct a set of names that the file at path may define. See loadable_constants_for_path for more details.


517
518
519
520
521
522
523
524
525
526
527
528
529
# File 'lib/active_support/dependencies.rb', line 517

def load_file(path, const_paths = loadable_constants_for_path(path))
  const_paths = [const_paths].compact unless const_paths.is_a? Array
  parent_paths = const_paths.collect { |const_path| const_path[/.*(?=::)/] || ::Object }

  result = nil
  newly_defined_paths = new_constants_in(*parent_paths) do
    result = Kernel.load path
  end

  autoloaded_constants.concat newly_defined_paths unless load_once_path?(path)
  autoloaded_constants.uniq!
  result
end

#load_missing_constant(from_mod, const_name) ⇒ Object

Load the constant named const_name which is missing from from_mod. If it is not possible to load the constant into from_mod, try its parent module using const_missing.


540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
# File 'lib/active_support/dependencies.rb', line 540

def load_missing_constant(from_mod, const_name)
  from_mod_name = real_mod_name(from_mod)
  unless qualified_const_defined?(from_mod_name) && Inflector.constantize(from_mod_name).equal?(from_mod)
    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

  file_path = search_for_file(path_suffix)

  if file_path
    expanded = File.expand_path(file_path)
    expanded.delete_suffix!(".rb")

    if loading.include?(expanded)
      raise "Circular dependency detected while autoloading constant #{qualified_name}"
    else
      require_or_load(expanded, qualified_name)

      if from_mod.const_defined?(const_name, false)
        log("constant #{qualified_name} autoloaded from #{expanded}.rb")
        return from_mod.const_get(const_name)
      else
        raise LoadError, "Unable to autoload constant #{qualified_name}, expected #{file_path} to define it"
      end
    end
  elsif mod = autoload_module!(from_mod, const_name, qualified_name, path_suffix)
    return mod
  elsif (parent = from_mod.module_parent) && parent != from_mod &&
        ! from_mod.module_parents.any? { |p| p.const_defined?(const_name, false) }
    # 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
      # 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.
      return parent.const_missing(const_name)
    rescue NameError => e
      raise unless e.missing_name? qualified_name_for(parent, const_name)
    end
  end

  name_error = uninitialized_constant(qualified_name, const_name, receiver: from_mod)
  name_error.set_backtrace(caller.reject { |l| l.start_with? __FILE__ })
  raise name_error
end

#load_once_path?(path) ⇒ Boolean

Returns:

  • (Boolean)

488
489
490
491
492
# File 'lib/active_support/dependencies.rb', line 488

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

#loadable_constants_for_path(path, bases = autoload_paths) ⇒ Object

Given path, a filesystem path to a ruby file, return an array of constant paths which would cause Dependencies to attempt to load this file.


447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
# File 'lib/active_support/dependencies.rb', line 447

def loadable_constants_for_path(path, bases = autoload_paths)
  path = path.chomp(".rb")
  expanded_path = File.expand_path(path)
  paths = []

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

    root_size = expanded_root.size
    next if expanded_path[root_size] != ?/

    nesting = expanded_path[(root_size + 1)..-1]
    paths << nesting.camelize unless nesting.blank?
  end

  paths.uniq!
  paths
end

#log(message) ⇒ Object


805
806
807
# File 'lib/active_support/dependencies.rb', line 805

def log(message)
  logger.debug("autoloading: #{message}") if logger && verbose
end

#mark_for_unload(const_desc) ⇒ Object

Mark the provided constant name for unloading. This constant will be unloaded on each request, not just the next one.


692
693
694
695
696
697
698
699
700
# File 'lib/active_support/dependencies.rb', line 692

def mark_for_unload(const_desc)
  name = to_constant_name const_desc
  if explicitly_unloadable_constants.include? name
    false
  else
    explicitly_unloadable_constants << name
    true
  end
end

#new_constants_in(*descs) ⇒ Object

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.


710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
# File 'lib/active_support/dependencies.rb', line 710

def new_constants_in(*descs)
  constant_watch_stack.watch_namespaces(descs)
  success = false

  begin
    yield # Now yield to the code that is to define new constants.
    success = true
  ensure
    new_constants = constant_watch_stack.new_constants

    return new_constants if success

    # Remove partially loaded constants.
    new_constants.each { |c| remove_constant(c) }
  end
end

#qualified_const_defined?(path) ⇒ Boolean

Is the provided constant path defined?

Returns:

  • (Boolean)

440
441
442
# File 'lib/active_support/dependencies.rb', line 440

def qualified_const_defined?(path)
  Object.const_defined?(path, false)
end

#qualified_name_for(mod, name) ⇒ Object

Returns the constant path for the provided parent and constant name.


532
533
534
535
# File 'lib/active_support/dependencies.rb', line 532

def qualified_name_for(mod, name)
  mod_name = to_constant_name mod
  mod_name == "Object" ? name.to_s : "#{mod_name}::#{name}"
end

#reference(klass) ⇒ Object

Store a reference to a class klass.


660
661
662
# File 'lib/active_support/dependencies.rb', line 660

def reference(klass)
  Reference.store klass
end

#remove_constant(const) ⇒ Object

:nodoc:


740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
# File 'lib/active_support/dependencies.rb', line 740

def remove_constant(const) #:nodoc:
  # Normalize ::Foo, ::Object::Foo, Object::Foo, Object::Object::Foo, etc. as Foo.
  normalized = const.to_s.delete_prefix("::")
  normalized.sub!(/\A(Object::)+/, "")

  constants = normalized.split("::")
  to_remove = constants.pop

  # 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.delete_suffix!(".rb")
    loaded.delete(expanded)
  end

  if constants.empty?
    parent = Object
  else
    # This method is robust to non-reachable constants.
    #
    # 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

  # 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)
    begin
      constantized = parent.const_get(to_remove, false)
    rescue NameError
      # The constant is no longer reachable, just skip it.
      return
    else
      constantized.before_remove_const if constantized.respond_to?(:before_remove_const)
    end
  end

  begin
    parent.instance_eval { remove_const to_remove }
  rescue NameError
    # The constant is no longer reachable, just skip it.
  end
end

#remove_unloadable_constants!Object

Remove the constants that have been autoloaded, and those that have been 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. as the environment will be in an inconsistent state, e.g. other constants may have already been unloaded and not accessible.


613
614
615
616
617
618
619
# File 'lib/active_support/dependencies.rb', line 613

def remove_unloadable_constants!
  log("removing unloadable constants")
  autoloaded_constants.each { |const| remove_constant const }
  autoloaded_constants.clear
  Reference.clear!
  explicitly_unloadable_constants.each { |const| remove_constant const }
end

#require_or_load(file_name, const_path = nil) ⇒ Object


397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
# File 'lib/active_support/dependencies.rb', line 397

def require_or_load(file_name, const_path = nil)
  file_name = file_name.chomp(".rb")
  expanded = File.expand_path(file_name)
  return if loaded.include?(expanded)

  Dependencies.load_interlock do
    # 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?
        # 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 || history.include?(expanded)
          result = load_file(*load_args)
        else
          enable_warnings { result = load_file(*load_args) }
        end
      else
        result = require file_name
      end
    rescue Exception
      loaded.delete expanded
      raise
    ensure
      loading.pop
    end

    # Record history *after* loading so first load gets warnings.
    history << expanded
    result
  end
end

#safe_constantize(name) ⇒ Object

Get the reference for class named name if one exists. Otherwise returns nil.


672
673
674
# File 'lib/active_support/dependencies.rb', line 672

def safe_constantize(name)
  Reference.safe_get(name)
end

#search_for_file(path_suffix) ⇒ Object

Search for a file in autoload_paths matching the provided suffix.


468
469
470
471
472
473
474
475
476
# File 'lib/active_support/dependencies.rb', line 468

def search_for_file(path_suffix)
  path_suffix += ".rb" unless path_suffix.end_with?(".rb")

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

#to_constant_name(desc) ⇒ Object

Convert the provided const desc to a qualified constant name (as a string). A module, class, symbol, or string may be provided.


729
730
731
732
733
734
735
736
737
738
# File 'lib/active_support/dependencies.rb', line 729

def to_constant_name(desc) #:nodoc:
  case desc
  when String then desc.delete_prefix("::")
  when Symbol then desc.to_s
  when Module
    real_mod_name(desc) ||
      raise(ArgumentError, "Anonymous modules have no name to be referenced by")
  else raise TypeError, "Not a valid constant descriptor: #{desc.inspect}"
  end
end

#unhook!Object


364
365
366
367
# File 'lib/active_support/dependencies.rb', line 364

def unhook!
  ModuleConstMissing.exclude_from(Module)
  Loadable.exclude_from(Object)
end

#will_unload?(const_desc) ⇒ Boolean

Will the provided constant descriptor be unloaded?

Returns:

  • (Boolean)

685
686
687
688
# File 'lib/active_support/dependencies.rb', line 685

def will_unload?(const_desc)
  autoloaded?(const_desc) ||
    explicitly_unloadable_constants.include?(to_constant_name(const_desc))
end