Consider the Ruby class Foo::Bar
.
The convention is for the 'Foo' namespace to be a module, but it could just as easily be a class:
module Foo; class Bar; end; end
Versus:
class Foo; class Bar; end; end
In the second case, Bar
is not an inner class of Foo
, it's just another constant defined on the singleton of Foo
. The superclass is Object in both cases and they only include the Kernel module. Their ancestor chains are identical.
So, besides operations you could make with Foo
depending on its class (instantiate if a class, extend/include if a module), does the nature of the namespace have any effect on Bar
? Are there compelling reasons to choose one many of name-spacing over another?
The only sort of weird things I see you can do are Foo::Bar.new.extend Foo
and Foo.new.class::Bar
respectively.
My own most-common use of a class defined in a class would be a helper struct/class that is meant to be only used internally by the class:
class Foo
Bar = Struct.new(:something) do
def digest
puts "eating #{something}"
end
end
def eat(something)
Bar.new(something).digest
end
end
The closest I found to this discussion is in "Using Class vs Module for packaging code in Ruby".
The most immediate benefit to using modules for namespacing is that you can use include
to import the namespace, and use the constants declared within it unqualified:
module Foo; class Bar; end; end
module Elsewhere
include Foo
Bar.new
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With