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 mod
@Squeegy's answer already tells you what to do, but I think it is equally important to understand why that works. And it's actually pretty simple: classes in Ruby are nothing special. They are just objects like any other object that get assigned to variables just like any other variable. More precisely: they are instances of the Class
class and they usually get assigned to constants (i.e. variables whose name starts with an uppercase letter).
So, just like you can alias any other object to multiple variables:
a = ''
b = a
a << 'Hello'
c = b
b << ', World!'
puts c # => Hello, World!
You can also alias classes to multiple variables:
class Foo; end
bar = Foo
p bar.new # => #
If you want to move the classes into the namespace instead of just aliasing them, you also need to set the original variables to some other object like nil
, in addition to @Squeegy's answer:
::A = nil
::B = nil