Namespaced classes in Ruby

We can write namspaced classes in ruby in two ways.

In the 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"
Advertisements

Author: Abhilash

Hi, this is Abhilash - Senior Programmer Analyst at CoMakeIT, specialised on web programming. Mainly working on Ruby On Rails platform since 2010.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s