反思嵌套命名空间

5

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

这是最有效的查找方式吗?我不喜欢将其转换为字符串。似乎应该有更优雅的解决方案。

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

Foo::Bar.new.parent #=> Foo
1个回答

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

@sawa 为什么以下代码不起作用?Foo::Bar::Baz.class_eval{ Module.nesting } # => []Foo::Bar::Baz.module_eval{ Module.nesting } # => [],以及 Foo::Bar.instance_eval{ Module.nesting } # => [] - rudolph9
@rudolph9 嵌套方法是像__dir__binding这样的少数几种方法之一,其中文字环境很重要。即使其他结构通常是等效的,也不能用其他结构替换它。 - sawa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接