Extending class from other module

A

Alexander Rysenko

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?
 
E

Eero Saynatkari

Alexander said:
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.
 
N

Noah Easterly

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

Jan Svitok

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.
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?

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/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,965
Messages
2,570,148
Members
46,710
Latest member
FredricRen

Latest Threads

Top