Sha256: ea46479b605397a5a01e7cca7cb3431490c166f0e20f4ada22d6faffa746d8a9

Contents?: true

Size: 1007 Bytes

Versions: 8

Compression:

Stored size: 1007 Bytes

Contents

class Module
  def find_const(const_name)
    if const_name[0..1] == '::'
      Object.find_const(const_name[2..-1])
    else
      nested_const_lookup(const_name)
    end
  end

  private

  # Doesn't do any caching since constants can change with remove_const
  def nested_const_lookup(const_name)
    constants = [ Object ]

    unless self == Object
      self.name.split('::').each do |part|
        constants.unshift(constants.first.const_get(part))
      end
    end

    parts = const_name.split('::')

    # from most to least specific constant, use each as a base and try
    # to find a constant with the name const_name within them
    constants.each do |const|
      # return the nested constant if available
      return const if parts.all? do |part|
        const = const.const_defined?(part) ? const.const_get(part) : nil
      end
    end

    # if we get this far then the nested constant was not found
    raise NameError, "uninitialized constant #{const_name}"
  end

end # class Module

Version data entries

8 entries across 8 versions & 2 rubygems

Version Path
extlib-0.9.5 lib/extlib/module.rb
extlib-0.9.3 lib/extlib/module.rb
extlib-0.9.4 lib/extlib/module.rb
thorero-0.9.4.1 lib/extlib/module.rb
thorero-0.9.4.2 lib/extlib/module.rb
thorero-0.9.4 lib/extlib/module.rb
thorero-0.9.4.4 lib/extlib/module.rb
thorero-0.9.4.3 lib/extlib/module.rb