From: Robert Klemme Date: 2006-04-19T19:01:42+09:00 Subject: Re: Nested scopes 2006/4/19, Yoann Guillot : > Hi, > > I just discovered a behavior of ruby that seems strange to me. > I have a module containing classes, and i'd like those classes to be > able to call some method of the module, so i tried different solutions : > > module Foo > def self.bar > puts "bar!" > end > > bar # works > > class Baz > # bar # doesn't work > # self.bar # doesn't work > Foo.bar # need to know the module name > end > end > > I'd like to be able to call the method from Foo::Baz without knowing the > name of the module, but the only way i found is to call Foo.bar from > inside Baz. > > Now if you replace "module Foo end" by "Module.new.module_eval {}"... > > Shouldn't ruby walk the nesting stack when it doesn't find a method name ? > Is this going to change in 2.0 ? No. But there's a simple cure (that we might even suggest to go into the std lib): class Module def outer name.split('::')[0..-2].inject(::Object){|cl,n| cl.const_get n} end end Now you can do module Foo def self.yeah; puts "yeah!" end class Bar p outer outer.yeah class Baz p outer end end end p outer and get Foo yeah! Foo::Bar Object :-) Kind regards robert -- Have a look: http://www.flickr.com/photos/fussel-foto/