开发者

Reflect on nested namespace

开发者 https://www.devze.com 2023-02-19 07:25 出处:网络
I am trying to find the root class/module of a nested namespace. Is this the most efficient way to find it? I don\'t like that I am converting to a string. It seems like there should be a more elegan

I am trying to find the root class/module of a nested namespace.

Is this the most efficient way to find it? I don't like that I am converting to a string. It seems like there should be a more elegant solution.

开发者_如何转开发
class Foo
   class Bar
     def parent
        Object.const_get self.class.to_s.split(/::/).first
     end
   end
end

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


There is 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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号