I'm trying to nest modules to create namespaces, but I'm not having
much luck. Let's say I have
module A
module B
def foo; @foo end
end
end
class Foo
include A
def initialize; @foo = 'foo' end
def bar; B::foo end
end
Calling Foo#bar raises "NoMethodError: undefined method `foo' for
Sam
···
A::B.Module". I would like to get "foo". What am I doing wrong?
Sam Stephenson wrote:
I'm trying to nest modules to create namespaces, but I'm not having
much luck. Let's say I have
You need to make foo a module method of B:
> module A
> module B
> def foo; @foo end
def B::foo; @foo; end
> end
> end
>
> class Foo
> include A
> def initialize; @foo = 'foo' end
> def bar; B::foo end
> end
Calling Foo#bar raises "NoMethodError: undefined method `foo' for
A::B.Module". I would like to get "foo". What am I doing wrong?
Sam
The way you had it originally, you were defining an _instance_ method of B. If you had included B in some class, you could then call foo as an method of instances of that class.
[re-sending an answer that didn't seem to make it for some reason]
Hi --
I'm trying to nest modules to create namespaces, but I'm not having
much luck. Let's say I have
> module A
> module B
> def foo; @foo end
> end
> end
>
> class Foo
> include A
> def initialize; @foo = 'foo' end
> def bar; B::foo end
> end
Calling Foo#bar raises "NoMethodError: undefined method `foo' for
A::B.Module". I would like to get "foo". What am I doing wrong?
The notation B::foo mean's B's own foo method:
module B
def B.foo
puts "hi"
end
end
B::foo # hi
To get your Foo object to have the method B#foo in its path, you'd
have to include the module (A::B) in Foo, or extend your object with
it.
David
···
On Wed, 15 Sep 2004, Sam Stephenson wrote:
--
David A. Black
dblack@wobblini.net
Okay, I see. But now Foo#bar gives nil.
So mixing in a module doesn't mix-in other modules "inside it" in the same way?
Sam
···
On Wed, 15 Sep 2004 06:34:01 +0900, Joel VanderWerf <vjoel@path.berkeley.edu> wrote:
You need to make foo a module method of B:
> module A
> module B
def B::foo; @foo; end
> end
> end
The way you had it originally, you were defining an _instance_ method of
B. If you had included B in some class, you could then call foo as an
method of instances of that class.
Got it. Thanks for the help!
Sam
···
On Wed, 15 Sep 2004 07:34:31 +0900, Joel VanderWerf <vjoel@path.berkeley.edu> wrote:
Nope. The namespace containment hierarchy is different from the
inheritance hierarchy.