Forum: Ruby Ruby Namespaces / Modules

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
F3b786a23390451fa67108781b0c8fed?d=identicon&s=25 unknown (Guest)
on 2006-03-10 01:15
(Received via mailing list)
If I'm in the middle of module A::B::C, and I want to reference a class
from A::B or from A::B::D, do I need to do ::A::B::Classname (or
::A::B::D::Classname)?

It seems a bit repititous to me.  A module shouldn't need to know it's
ancestors all the way up - just what it needs to use.  Having to keep
track couples modules to a tree and obstructs refactoring.

So, what say the veteran Rubyists?
912c61d9da47754de7039f4271334a9f?d=identicon&s=25 unknown (Guest)
on 2006-03-10 01:28
(Received via mailing list)
Quoting eastcoastcoder@gmail.com:

> If I'm in the middle of module A::B::C, and I want to reference a
> class from A::B or from A::B::D, do I need to
> do ::A::B::Classname (or ::A::B::D::Classname)?
>
> It seems a bit repititous to me.  A module shouldn't need to know
> it's ancestors all the way up - just what it needs to use.
> Having to keep track couples modules to a tree and obstructs
> refactoring.
>
> So, what say the veteran Rubyists?

Try it!

 module A
   module B
     class Foo
     end
     module D
       class Bar
       end
     end
   end
   module C
     p B::Foo
     p B::D::Bar
   end
 end

-mental
851246810c70dbfcc1815c636b054562?d=identicon&s=25 George Ogata (Guest)
on 2006-03-10 01:40
(Received via mailing list)
mental@rydia.net writes:

>>
>        end
>      end
>    end
>    module C
>      p B::Foo
>      p B::D::Bar
>    end
>  end

It's also worth pointing out that:

  class A::B::Foo
    p C
  end

is different to:

  module A
    module B
      class Foo
        p C
      end
    end
  end

The latter may reference A::B::C or A::C, whereas the former cannot.
F3b786a23390451fa67108781b0c8fed?d=identicon&s=25 unknown (Guest)
on 2006-03-10 01:46
(Received via mailing list)
> The latter may reference A::B::C or A::C, whereas the former cannot.

Intersting... why is that?
851246810c70dbfcc1815c636b054562?d=identicon&s=25 George Ogata (Guest)
on 2006-03-10 02:19
(Received via mailing list)
eastcoastcoder@gmail.com writes:

>> The latter may reference A::B::C or A::C, whereas the former cannot.
>
> Intersting... why is that?

Doing "module X::Y::Z" (or "class X::Y::Z") will bring only X::Y::Z::*
constants into scope.  Constants from outer modules (X::Y::*, X::*)
aren't brought in.  Thus, to get all the nested namespaces in scope,
you need to open each one explicitly.

It's been debated:

http://rubyurl.com/1NH
http://rubyurl.com/0KZ
This topic is locked and can not be replied to.