Namespaced classes in Ruby

We can write namspaced classes in ruby in two ways.

Normal way we can wrap the class inside a module. Lets say the module name as ‘MyModule’.
And the constants we define inside this module are accessed as follows:


module MyModule
    CONST1 = 1
    class Myclass
       CONST2 = 2
       def name
          "This is my name"
       end

       def const_1
         CONST1
       end

       def const_2
          CONST2
       end
    end
end

p MyModule::Myclass.new.name
p MyModule::Myclass.new.const_1
p MyModule::Myclass.new.const_2

The other way of doing this is the short way of writing the class name with module name and two columns.
As you can see, the const_1 is accessed as prefixing the module name with two columns.

module MyModule
    CONST1 = 1
end

class MyModule::Myclass
    CONST2 = 2
    
    def name
       "This is my name"
    end
    
    def const_1
        MyModule::CONST1        
    end
    
    def const_2
        CONST2
    end
end

p MyModule::Myclass.new.name
p MyModule::Myclass.new.const_1
p MyModule::Myclass.new.const_2

There is an another way of doing this, that may looks strange to most of the people. Nested classes.

class Myclass
  def name
     "This is my name"
  end

  def my_class_2_name
     Myclass2.new.name
  end

  class Myclass2
    def name
       Myclass.new.name
    end
  end
end

> p Myclass.new.name
> "This is my name"
> p Myclass.new.my_class_2_name
> "This is my name"

The two printing works. So what is the use of these nested classes? Hmmm. It is just namespacing the second class and it tells, somehow it relates to first class even though there is no relation between these two classes.

> p Myclass2.new.name
> uninitialized constant Myclass2

We cannot access Myclass2 without specifying the namespace ( Myclass )

> p Myclass::Myclass2.new.name
> "This is my name"
Advertisement