Victor Victor - 1 month ago 7
Ruby Question

Ruby: Do something when extending an instance with a module

I'd like to execute some code when an instance is extended with Object#extend. A bit like

initialize
when instantiating a class but for a module.

Here is the extended documentation example:

module Mod
def hello
"Hello from Mod.\n"
end
end

class GoodKlass
def hello
"Hello from GoodKlass.\n"
end
end

class BadKlass
# something totally different
end

good = GoodKlass.new
good.hello #=> "Hello from GoodKlass.\n"
good.extend(Mod) #=> #<GoodKlass:0x401b3bc8>
good.hello #=> "Hello from Mod.\n"


For example I'd like to display a warning or raise if
Mod
is used to
expand
something else than an instance of
GoodKlass
:

bad = BadKlass.new
bad.extend(Mod) #=> raise "Mod cannot extend BadKlass"

Answer

You can define self.extended in the module:

module Mod
  def self.extended(base)
    raise "Cannot extend #{base}" unless base.is_a?(GoodKlass)
  end

  def hello
    "Hello from Mod.\n"
  end
end