Forum: Ruby Ruby namespacing with a class vs. module?

B5c20f697f141bfc00b1b57e581101c9?d=identicon&s=25 Benjamin F. (benjamin_f)
on 2013-10-25 18:15
Duplicate of a question I've recently asked on stackoverflow:
http://stackoverflow.com/questions/19574319/ruby-n...

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

An answer there suggests the benefit of using modules as namespaces is
that ability to mix them into to other code and gain the ability to use
Constants defined in the mixed-in module without the namespace.  To me,
that's an edge case of a library that is meant to be mixed in.  e.g of
all the Net:: libraries in ruby's standard library, does anyone mix-in
Net?  https://github.com/ruby/ruby/tree/trunk/lib/net
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.