Flip on nested namespace

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

Is this the most effective way to find it? I do not like what I convert to 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
+5
source share
1 answer

Exist 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
+7
source

All Articles