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

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

Another example that would be more practical in the real world is to have mixins that are only applied by subclasses.

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)