introspection.rb 1.9 KB
Newer Older
1 2
require 'active_support/inflector'

3 4 5
class Module
  # Returns the name of the module containing this one.
  #
X
Xavier Noria 已提交
6
  #   M::N.parent_name # => "M"
7
  def parent_name
A
Alexey Gaziev 已提交
8 9 10
    if defined? @parent_name
      @parent_name
    else
11 12 13
      @parent_name = name =~ /::[^:]+\Z/ ? $`.freeze : nil
    end
  end
J
Jeremy Kemper 已提交
14

15 16 17 18 19 20 21 22
  # Returns the module which contains this one according to its name.
  #
  #   module M
  #     module N
  #     end
  #   end
  #   X = M::N
  #
X
Xavier Noria 已提交
23 24
  #   M::N.parent # => M
  #   X.parent    # => M
25 26 27
  #
  # The parent of top-level and anonymous modules is Object.
  #
X
Xavier Noria 已提交
28 29
  #   M.parent          # => Object
  #   Module.new.parent # => Object
30 31
  #
  def parent
32
    parent_name ? ActiveSupport::Inflector.constantize(parent_name) : Object
33
  end
34

35 36 37 38 39 40 41 42 43
  # 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
  #
X
Xavier Noria 已提交
44 45 46
  #   M.parents    # => [Object]
  #   M::N.parents # => [M, Object]
  #   X.parents    # => [M, Object]
47 48 49 50 51 52
  #
  def parents
    parents = []
    if parent_name
      parts = parent_name.split('::')
      until parts.empty?
53
        parents << ActiveSupport::Inflector.constantize(parts * '::')
54
        parts.pop
J
Jeremy Kemper 已提交
55
      end
56 57 58 59
    end
    parents << Object unless parents.include? Object
    parents
  end
60

61 62
  def local_constants #:nodoc:
    constants(false)
63 64
  end

65 66 67 68 69 70 71 72 73 74 75
  # *DEPRECATED*: Use +local_constants+ instead.
  #
  # Returns the names of the constants defined locally as strings.
  #
  #   module M
  #     X = 1
  #   end
  #   M.local_constant_names # => ["X"]
  #
  # This method is useful for forward compatibility, since Ruby 1.8 returns
  # constant names as strings, whereas 1.9 returns them as symbols.
76
  def local_constant_names
A
Alexey Gaziev 已提交
77
    ActiveSupport::Deprecation.warn 'Module#local_constant_names is deprecated, use Module#local_constants instead', caller
78
    local_constants.map { |c| c.to_s }
79
  end
80
end