From: Ragav Satish Date: 2008-10-04T17:10:55+09:00 Subject: Re: module scope not clear to me Nit Khair wrote: > I had a program which inherits from a superclass. It also has > common/convenience methods in a module. > > > require 'common' > include 'Common' > class Prog < Application > f = Obj.new > g = Foo.new > #... etc ... > > > > Some convenience methods rely on a variable being set in the superclass. > (I know that does not sound good but it shields this detail from > individual programs.) > > Then i refactored ... moved a lot of functionality out from the program > to objects it was creating. I would guess that these objects should > _not_ be able to call the module methods. Suprisingly, they were. > > The problem came up that the variable was obviously not set when called > by these objects, (since the class of the module was now the object's > class not the program's class.) > > So my basic question is: if a program includes a module, can all its > composed objects also call on the module. Depends on where the module is included. If its included at the top level (outside of another class/module) then it's mixed into the Object class from which all other classes ultimately derive , so method lookup on any object will always find it. module M def foo; puts "module foo" end end class C; end # method name resolution chain before include p C.ancestors #=> [C, Object, Kernel] include M # including at top level has M as the p C.ancestors #=> [C, Object, M, Kernel] C.new.foo #=> module foo # heck you can even call it on "M", "C" since they are also objects M.foo #=> module foo C.foo #=> module foo. Once you include a module at the *top level* you are creating a set of methods accessible from anywhere. --Cheers --Ragav -- Posted via http://www.ruby-forum.com/.