反映嵌套命名空间

时间:2011-03-24 18:26:14

标签: ruby namespaces nested

我试图找到嵌套命名空间的根类/模块。

这是找到它的最有效方法吗?我不喜欢我转换成字符串。似乎应该有一个更优雅的解决方案。

class Foo
   class Bar
     def parent
        Object.const_get self.class.to_s.split(/::/).first
     end
   end
end

Foo::Bar.new.parent #=> Foo

1 个答案:

答案 0 :(得分:7)

Module.nesting

module Foo
  module Bar
    module Baz
      p Module.nesting       # => [Foo::Bar::Baz, Foo::Bar, Foo]
      p Module.nesting.last  # => Foo
    end
  end
end