Sha256: 676c6d53926c19c4b0c8178f496964ea5568613fefaf58eaa9e224ab81ad2b95

Contents?: true

Size: 1.36 KB

Versions: 6

Compression:

Stored size: 1.36 KB

Contents

require 'core_ext/inflector'

class Module
  # Returns the name of the module containing this one.
  #
  #   M::N.parent_name # => "M"
  def parent_name
    if defined? @parent_name
      @parent_name
    else
      @parent_name = name =~ /::[^:]+\Z/ ? $`.freeze : nil
    end
  end

  # Returns the module which contains this one according to its name.
  #
  #   module M
  #     module N
  #     end
  #   end
  #   X = M::N
  #
  #   M::N.parent # => M
  #   X.parent    # => M
  #
  # The parent of top-level and anonymous modules is Object.
  #
  #   M.parent          # => Object
  #   Module.new.parent # => Object
  def parent
    parent_name ? CoreExt::Inflector.constantize(parent_name) : Object
  end

  # Returns all the parents of this module according to its name, ordered from
  # nested outwards. The receiver is not contained within the result.
  #
  #   module M
  #     module N
  #     end
  #   end
  #   X = M::N
  #
  #   M.parents    # => [Object]
  #   M::N.parents # => [M, Object]
  #   X.parents    # => [M, Object]
  def parents
    parents = []
    if parent_name
      parts = parent_name.split('::')
      until parts.empty?
        parents << CoreExt::Inflector.constantize(parts * '::')
        parts.pop
      end
    end
    parents << Object unless parents.include? Object
    parents
  end

  def local_constants #:nodoc:
    constants(false)
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
core_ext-0.0.6 lib/core_ext/module/introspection.rb
core_ext-0.0.5 lib/core_ext/module/introspection.rb
core_ext-0.0.4 lib/core_ext/module/introspection.rb
core_ext-0.0.3 lib/core_ext/module/introspection.rb
core_ext-0.0.2 lib/core_ext/module/introspection.rb
core_ext-0.0.1 lib/core_ext/module/introspection.rb