3

I am new to Ruby but have been looking through some source code. I came across the kind of structures shown below in some source code (names of modules, classes not the real ones)

module ModuleOne

class MyClass

module CommonModule

# code ....

end # module CommonModule

end # class MyClass

end # module ModuleOne

or this example

module ModuleOne

  class MyClass

    class MyClassTwo

#code  ............

  end #class MyClassTwo

    end #class MyClass

      end #module ModuleOne

From my reading so far I know about wrapping classes in modules, but I haven't heard of the kinds of wrapping (modules inside modules or classes in classes for example) shown above. Can I ask, 1. Is this good practice and commonly done ? 2. What is the advantage of structuring code in this way ?

Thanks for any comments or pointers

Dave

sawa
  • 165,429
  • 45
  • 277
  • 381
Davet
  • 334
  • 1
  • 3
  • 15

1 Answers1

4

Nesting is done to encapsule constants, which modules are special cases of. In other words, they are used for namespacing. When you want a particular module to be accessible only within the context of a certain module, you should do nesting. By doing so, that module will not be accessible by default from outside; you would have to prefix the namespace to do so. When you have too many layers of nesting, or when the module body is long, it would become hard to follow it in the code, so a good way in such case is to write the whole namespace.

module ModuleOne
  ...
end

class ModuleOne::MyClass
  ...
end

class ModuleOne::MyClass::MyClassTwo
  ...
end
sawa
  • 165,429
  • 45
  • 277
  • 381