Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby namespacing with a class vs. module?

Tags:

ruby

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".

like image 479
BF4 Avatar asked Oct 24 '13 18:10

BF4


1 Answers

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
like image 84
Ash Wilson Avatar answered Oct 12 '22 10:10

Ash Wilson