module ActiveSupport::Dependencies

def autoload_module!(into, const_name, qualified_name, path_suffix)

set of constants that are to be unloaded.
the directory was loaded from a reloadable base path, it is added to the
assigned to +into+'s constants with the name +const_name+. Provided that
matching the expected path suffix. If found, the module is created and
Attempt to autoload the provided module name by searching for a directory
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
  autoloaded_constants << qualified_name unless autoload_once_paths.include?(base_path)
  mod
end

def autoloadable_module?(path_suffix)

returned.
Instead of returning a boolean, the autoload base for this module is
Does the provided path_suffix correspond to an autoloadable module?
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

def autoloaded?(desc)

Determine if the given constant has been automatically loaded.
def autoloaded?(desc)
  return false if desc.is_a?(Module) && desc.anonymous?
  name = to_constant_name desc
  return false unless qualified_const_defined? name
  return autoloaded_constants.include?(name)
end

def clear

def clear
  log_call
  loaded.clear
  remove_unloadable_constants!
end

def constantize(name)

Raises an exception if referenced class does not exist.
Get the reference for class named +name+.
def constantize(name)
  Reference.get(name)
end

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

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.replace(message % file_name)
    load_error.copy_blame!(load_error)
  end
  raise
end

def hook!

def hook!
  Object.class_eval { include Loadable }
  Module.class_eval { include ModuleConstMissing }
  Exception.class_eval { include Blamable }
end

def load?

def load?
  mechanism == :load
end

def load_file(path, const_paths = loadable_constants_for_path(path))

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

autoloaded, and will be removed when Dependencies.clear is next called.
addition of these constants. Each that is defined will be marked as
constant names. When loading the file, Dependencies will watch for the
Load the file at the provided path. +const_paths+ is a set of qualified
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
  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!
  log "loading #{path} defined #{newly_defined_paths * ', '}" unless newly_defined_paths.empty?
  result
end

def load_missing_constant(from_mod, const_name)

module using +const_missing+.
it is not possible to load the constant into from_mod, try its parent
Load the constant named +const_name+ which is missing from +from_mod+. If
def load_missing_constant(from_mod, const_name)
  log_call from_mod, const_name
  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
  raise NameError.new("#{from_mod} is not missing constant #{const_name}!", const_name) if from_mod.const_defined?(const_name, false)
  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.sub!(/\.rb\z/, '')
    if loaded.include?(expanded)
      raise "Circular dependency detected while autoloading constant #{qualified_name}"
    else
      require_or_load(expanded, qualified_name)
      raise LoadError, "Unable to autoload constant #{qualified_name}, expected #{file_path} to define it" unless from_mod.const_defined?(const_name, false)
      return from_mod.const_get(const_name)
    end
  elsif mod = autoload_module!(from_mod, const_name, qualified_name, path_suffix)
    return mod
  elsif (parent = from_mod.parent) && parent != from_mod &&
        ! from_mod.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 = NameError.new("uninitialized constant #{qualified_name}", const_name)
  name_error.set_backtrace(caller.reject {|l| l.starts_with? __FILE__ })
  raise name_error
end

def load_once_path?(path)

def load_once_path?(path)
  # to_s works around a ruby1.9 issue where #starts_with?(Pathname) will always return false
  autoload_once_paths.any? { |base| path.starts_with? base.to_s }
end

def loadable_constants_for_path(path, bases = autoload_paths)

file.
constant paths which would cause Dependencies to attempt to load this
Given +path+, a filesystem path to a ruby file, return an array of
def loadable_constants_for_path(path, bases = autoload_paths)
  path = $` if path =~ /\.rb\z/
  expanded_path = File.expand_path(path)
  paths = []
  bases.each do |root|
    expanded_root = File.expand_path(root)
    next unless %r{\A#{Regexp.escape(expanded_root)}(/|\\)} =~ expanded_path
    nesting = expanded_path[(expanded_root.size)..-1]
    nesting = nesting[1..-1] if nesting && nesting[0] == ?/
    next if nesting.blank?
    paths << nesting.camelize
  end
  paths.uniq!
  paths
end

def log(msg)

def log(msg)
  logger.debug "Dependencies: #{msg}" if log_activity?
end

def log_activity?

def log_activity?
  logger && log_activity
end

def log_call(*args)

def log_call(*args)
  if log_activity?
    arg_str = args.collect { |arg| arg.inspect } * ', '
    /in `([a-z_\?\!]+)'/ =~ caller(1).first
    selector = $1 || '<unknown>'
    log "called #{selector}(#{arg_str})"
  end
end

def mark_for_unload(const_desc)

unloaded on each request, not just the next one.
Mark the provided constant name for unloading. This constant will be
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

def new_constants_in(*descs)

and will be removed immediately.
exception, any new constants are regarded as being only partially defined
If the provided block does not run to completion, and instead raises an

inner call will not be reported in this one.
block calls +new_constants_in+ again, then the constants defined within the
its execution. Constants may only be regarded as 'new' once -- so if the
Run the provided block and detect the new constants that were loaded during
def new_constants_in(*descs)
  log_call(*descs)
  constant_watch_stack.watch_namespaces(descs)
  aborting = true
  begin
    yield # Now yield to the code that is to define new constants.
    aborting = false
  ensure
    new_constants = constant_watch_stack.new_constants
    log "New constants: #{new_constants * ', '}"
    return new_constants unless aborting
    log "Error during loading, removing partially loaded constants "
    new_constants.each { |c| remove_constant(c) }.clear
  end
  []
end

def qualified_const_defined?(path)

Is the provided constant path defined?
def qualified_const_defined?(path)
  Object.qualified_const_defined?(path.sub(/^::/, ''), false)
end

def qualified_name_for(mod, name)

Returns the constant path for the provided parent and constant name.
def qualified_name_for(mod, name)
  mod_name = to_constant_name mod
  mod_name == "Object" ? name.to_s : "#{mod_name}::#{name}"
end

def reference(klass)

Store a reference to a class +klass+.
def reference(klass)
  Reference.store klass
end

def remove_constant(const) #:nodoc:

:nodoc:
def remove_constant(const) #:nodoc:
  # Normalize ::Foo, ::Object::Foo, Object::Foo, Object::Object::Foo, etc. as Foo.
  normalized = const.to_s.sub(/\A::/, '')
  normalized.sub!(/\A(Object::)+/, '')
  constants = normalized.split('::')
  to_remove = constants.pop
  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
  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)
    begin
      constantized = parent.const_get(to_remove, false)
    rescue NameError
      log "the constant #{const} is not reachable anymore, skipping"
      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
    log "the constant #{const} is not reachable anymore, skipping"
  end
end

def remove_unloadable_constants!

may have already been unloaded and not accessible.
as the environment will be in an inconsistent state, e.g. other constants
The callback implementation should be restricted to cleaning up caches, etc.

to its class/module if it implements +before_remove_const+.
marked for unloading. Before each constant is removed a callback is sent
Remove the constants that have been autoloaded, and those that have been
def remove_unloadable_constants!
  autoloaded_constants.each { |const| remove_constant const }
  autoloaded_constants.clear
  Reference.clear!
  explicitly_unloadable_constants.each { |const| remove_constant const }
end

def require_or_load(file_name, const_path = nil)

def require_or_load(file_name, const_path = nil)
  log_call file_name, const_path
  file_name = $` if file_name =~ /\.rb\z/
  expanded = File.expand_path(file_name)
  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
  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
    else
      log "requiring #{file_name}"
      result = require file_name
    end
  rescue Exception
    loaded.delete expanded
    raise
  end
  # Record history *after* loading so first load gets warnings.
  history << expanded
  result
end

def safe_constantize(name)

Otherwise returns +nil+.
Get the reference for class named +name+ if one exists.
def safe_constantize(name)
  Reference.safe_get(name)
end

def search_for_file(path_suffix)

Search for a file in autoload_paths matching the provided suffix.
def search_for_file(path_suffix)
  path_suffix = path_suffix.sub(/(\.rb)?$/, ".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

def to_constant_name(desc) #:nodoc:

:nodoc:
A module, class, symbol, or string may be provided.
Convert the provided const desc to a qualified constant name (as a string).
def to_constant_name(desc) #:nodoc:
  case desc
    when String then desc.sub(/^::/, '')
    when Symbol then desc.to_s
    when Module
      desc.name.presence ||
        raise(ArgumentError, "Anonymous modules have no name to be referenced by")
    else raise TypeError, "Not a valid constant descriptor: #{desc.inspect}"
  end
end

def unhook!

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

def will_unload?(const_desc)

Will the provided constant descriptor be unloaded?
def will_unload?(const_desc)
  autoloaded?(const_desc) ||
    explicitly_unloadable_constants.include?(to_constant_name(const_desc))
end