Ruby namespacing with a class vs. module?

Duplicate of a question I’ve recently asked on stackoverflow:
http://stackoverflow.com/questions/19574319/ruby-namespacing-with-a-class-vs-module/19574482

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs