Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflect on nested namespace

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
like image 597
The Who Avatar asked Mar 24 '11 18:03

The Who


1 Answers

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
like image 63
sawa Avatar answered Oct 05 '22 21:10

sawa