# Class inheriting from class within the namespace

**URL:** <https://www.ruby-forum.com/t/class-inheriting-from-class-within-the-namespace/74595>\
**Category:** Ruby\
**Created:** [November 7, 2006, 10:49am UTC](https://www.ruby-forum.com/t/class-inheriting-from-class-within-the-namespace/74595 "2006-11-07T10:49:24Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![phrogz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/2acd7d/32.png) [@phrogz](https://www.ruby-forum.com/u/phrogz)\
**Post date:** [November 7, 2006, 10:49am UTC](https://www.ruby-forum.com/t/class-inheriting-from-class-within-the-namespace/74595/1 "2006-11-07T10:49:24Z")

</div>

Tree structures are interesting. Often the root of the tree is used as a  
handle for the tree itself. However, the tree often has additional  
methods beyond that of the root node.

I couldn’t figure out how to do this simply via inheritance due to  
chicken-and-egg problems with namespacing:

class Tree \< Tree::Node  
class Node  
end  
end  
#=\> chicken-and-egg.rb:1: uninitialized constant Tree (NameError)

I came up with two alternative techniques to achieve the same goal. I’m  
not wild about the way either are handled by RDoc (though the first is  
substantially better):

# Technique 1: Using modules

class Tree  
module NodeStuff  
#…all the meat here…  
end  
include NodeStuff

```
class Node
  include NodeStuff
end

```

end

# Technique 2: Conjur the chicken first, and kill it later

class TmpTreeNode  
# …all the meat here…  
end  
class Tree \< TmpTreeNode  
Node = TmpTreeNode  
end  
Object.class\_eval{ remove\_const( :TmpTreeNode ) }

Ideally, IMO, Ruby would let me do this:

# No “Tree” module or class has yet been defined;

# it is a pure namespace at this point

class Tree::Node  
# …all the meat here…  
end

# Now Tree is a class

class Tree \< Tree::Node  
end

I don’t have any question, and it’s not important enough to me to make  
an RCR for the above. I just thought I’d share these thoughts with the  
world.

---

<div class="post-metadata">

**Author:** ![phrogz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/2acd7d/32.png) [@phrogz](https://www.ruby-forum.com/u/phrogz)\
**Post date:** [November 7, 2006, 10:49am UTC](https://www.ruby-forum.com/t/class-inheriting-from-class-within-the-namespace/74595/2 "2006-11-07T10:49:31Z")

</div>

Gavin K. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> end  
> #=\> chicken-and-egg.rb:1: uninitialized constant Tree (NameError)

Why wouldn’t you do this?

module TreeStuff  
class Node  
end  
class Tree \< Node  
end  
end

A tree does more than a node (you say), so a tree is a subclass of node  
(“a node and then some”). The pair are wrapped up in a module to isolate  
their namespace.

Of course I could be missing some other desideratum. m.
