Extending class from other module

1st question: If I got it right, modules in Ruby can be used as
namespaces. Is it ok? Is there some other (preffered) way?

2nd question: I need to extend some class from one module in another
one. Basically I do something like this:

module Mod1
class A1
end

class B2 < Mod2::B1
end
end

module Mod2
class B1
end
end

But this doesn’t really work (seems like B1 isn’t really found). How can
I do such a thing?

Alexander R. wrote:

1st question: If I got it right, modules in Ruby can be used as
namespaces. Is it ok? Is there some other (preffered) way?

That is the way to do it.

2nd question: I need to extend some class from one module in another
one. Basically I do something like this:

module Mod1
class A1
end

class B2 < Mod2::B1
end
end

module Mod2
class B1
end
end

But this doesn’t really work (seems like B1 isn’t really found). How can
I do such a thing?

You need to flip those around. You cannot inherit from
Mod2::B1 before it is defined.

module Mod1
class A1
end
end
module Mod2
class B1
end
end
class Mod1::B2 < Mod2::B1
end

On 8/29/06, Alexander R. [email protected] wrote:

1st question: If I got it right, modules in Ruby can be used as
namespaces. Is it ok? Is there some other (preffered) way?

Exactly. Look for example at test/unit[1], or rails[2] as they contain
a lot of classes divided into modules for namespace separation.

module Mod2
class B1
end
end

But this doesn’t really work (seems like B1 isn’t really found). How can
I do such a thing?

The problem is in the order of evaluation. Install rcov (gem install
rcov) and see for yourself what lines ruby has read already and what
not.

I guess the problem is that B1 is not known to ruby yet. You can fix
that by reversing the order, or just declaring the class without any
content:

module Mod2
class B1
end
end

module Mod1
class B2 < Mod2::B1
def xxx…

end
end
end

module Mod2
class B1
def yyy

end
end
end

I don’t have ruby installed now, so I can’t verify these things, so
please take it as such.

[1] http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/index.html
[2] http://api.rubyonrails.com/