Hi -

On Sat, 4 Aug 2007, Kenneth McDonald wrote:

> Do modules not execute their own code (such as the 'p "Testing"') below in 
> their own namespace, then?

They do execute their own code, but the code being executed is an
instance method definition.  Like 'p "testing"', the method definition
gets executed when it's encountered.  But it still has a particular
effect, namely creating an instance method for objects that use this
module.

> I'm doing something that's not at all 
> object-oriented, and simply want to ensure that a bunch of methods don't leak 
> out into the global namespace. One module will define those methods, and 
> other modules (not classes, unless I really have to hack it that way) will 
> use the first module, eg.
>
> module Test
>   p "Testing"
>   eval("def foo\np 'OK'\nend")
> end
>
> module Run
>   include Test
>   foo
> end
>
> The above doesn't work, for the reasons you gave, but I still don't 
> understand the semantics of why not, I'm afraid. No doubt my Python way of 
> thinking. 
[...]
> Now, since that interpretation is obviously incorrect in Ruby, could someone 
> provide details as to what is actually going on? If possible, I prefer 
> explanations of the 'behind-the-scenes' stuff--how variables are looked up, 
> namespaces are defined, etc., as understanding the background mechanisms will 
> then make everything else pretty easy.

Basically, it works like this: every time you send a message to an
object, the object searches along a lookup path consisting of classes
and modules, looking for a corresponding method.  The path includes
the object's class, and also any modules that the class includes, and
modules included by those modules, etc.

Modules are themselves objects.  That means that when you send a
message to a module, it looks for that method in its lookup path.
However, a module does not lie in its own lookup path (unless you
include it in itself).

A module (and a class) has a kind of dual identity: it's a repository
of instance methods for other objects, and it's also an object in its
own right.  These two roles are fairly strictly delineated.  You can't
do this:

   class C
     def x
     end
   end

   C.x

because x is defined for the use of instances of C, not C itself.
Similarly, you can't do this:

   module M
     def x
     end
   end

   M.x

for the same reason.  And this:

   module M
     def x
     end

     x
   end

is exactly the same: you're sending the message "x" to the module
object M, but that object doesn't have an x method.


David

-- 
* Books:
   RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242)
   RUBY FOR RAILS (http://www.manning.com/black)
* Ruby/Rails training
     & consulting:  Ruby Power and Light, LLC (http://www.rubypal.com)