Nathan Long Nathan Long - 1 month ago 7
Ruby Question

Why would we put a module inside a class in Ruby?

In Ruby, I see that it can be useful to put classes inside modules for the sake of namespacing. I also see that it's possible to put modules inside classes. But I don't see why you'd do that.

Modules are generally mixed into classes, right? So, what would be the purpose of defining a module inside a class?

Answer Source

We could use it when writing ape-like code like this:

class DrugDealer
  module Drug
    def happy?; true; end
  end

  def approach(victim)
    victim.extend Drug
  end
end

o = Object.new
DrugDealer.new.approach(o)
o.happy? # => true

Edit

Maybe a better example is the following. This is actually somewhat practical -- mixins that are only applied by subclasses.

It is useful when some facets of a thing apply to some subclasses and other facets apply to other subclasses, without there being enough order in the way these aspects apply to make way for a clear class hierarchy (tree). Think multiple inheritance! A simplified example:

class Person
  def handshake
    :sloppy
  end

  def mind_contents
    :spam
  end

  module Proper
    def handshake
      :firm
    end
  end

  module Clever
    def mind_contents
      :theories
    end
  end
end

class Professor < Person
  include Proper
  include Clever

  # ...
end

And so on. Kind of nice, when used sensibly. Even super calls and constructors (I didn't define any here though) flow through all the mixins and classes the way I want them to.