Ruby - Using Mix-Ins with Namespaces and Classes

Introduction

You can use modules to define namespaces using the following code:

Demo

module ToolBox 
  class Ruler # from   w ww.  jav a2s.c  o m
    attr_accessor :length 
  end 
end 

module Country 
  class Ruler 
    attr_accessor :name 
  end 
end 

a = ToolBox::Ruler.new 
a.length = 50 
b = Country::Ruler.new 
b.name = "test"

Here, the Ruler classes were accessed by directly addressing them via their respective modules as ToolBox::Ruler and Country::Ruler.

Include module

include Country 
c = Ruler.new 
c.name = "test" 

The Country module's contents which is the Ruler class are brought into the current scope.

You can use Ruler as if it's a local class.

To use the Ruler class located under ToolBox, you can still refer to it directly as ToolBox::Ruler.

Related Topic