Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add existing classes into a module

I have some existing ruby classes in a app/classes folder:

class A
   ...
end

class B
   ...
end

I'd like to group those classes in a module MyModule

I know I could do like:

module MyModule
  class A
      ...
   end
   class B
      ...
   end
end

but is there a meta programming shortcut that could do the same so I could "import" all the existing classes ?

Thanks, Luc

like image 864
Luc Avatar asked Aug 27 '10 07:08

Luc


People also ask

How do you import a class in Python?

Importing a specific class by using the import command You just have to make another . py file just like MyFile.py and make the class your desired name. Then in the main file just import the class using the command line from MyFile import Square.

Can we have a class inside a module?

You may use nested classes without fear of encountering this bug. Show activity on this post. You'd be more accurate to say that 'class in Ruby is a module'! Note that modules can not be instantiated.


1 Answers

module Foo
  A = ::A
  B = ::B
end

Foo::A.new.bar

Note that the :: prefix on a constant starts searchign the global namespace first. Like a leading / on a pathname. This allows you differentiate the global class A from the modularized constant Foo::A.

like image 135
Alex Wayne Avatar answered Sep 28 '22 12:09

Alex Wayne