On Mon, Jun 14, 2010 at 7:18 PM, Eric MSP Veith
<eveith / wwweb-library.net> wrote:

> I'm trying to understand the way Ruby resolves symbol names and how the
> require statement fits in.

The code is executed in a linear fashion.


> - ---%<---
> # a.rb:
> require 'a/b'

At this point, the code in a/b.rb is read and evaluated.  So, jump
down to there.

> module Foo
>  
>
>  
>   ﺺ®>  ®
>  
> end
>
>
> # a/b.rb:
> require 'a'
>
> module Foo
>   ﺺﺺ

This expects Foo::A to exist, but the way you have written you code,
with this being required before Foo::A is defined in the a.rb code, it
won't exist yet.

>   >  
>  
>  
> end
> - --->%---
>
> With the above code, I get a "missing symbol" error. Placing the "require
> 'a/b'" statement within the Foo::A class remedies it.

This is because by that time Ruby is aware of the existence of the
Foo:A class, so your code in a/b.rb can execute.

> Is there any best practice regarding such a situation? While this examples
> constructed, I'm trying to create a namespace hierarchy in which a class on
> top mediates several others that live further below the hiearchy, but don't
> derive from it.

Just move your require statements.

If a.rb is defining stuff needed by a/b.rb, but you want a require of
a.rb to also load a/b.rb, then put that require somewhere else. It
doesn't have to be in the class definition. You can do that, but were
it me, I'd just put it along with any other similar require statements
at the end of the file, or at least after the class definition that
those files are depending on.


Kirk Haines
Developer
Engine Yard