Is it possible to override #initialize in a Ruby module?

Ok, well in Ruby 1.9 you could add functionality to the new class method...

module Mo
  def new(*var)
    additional_initialize(*var)
    super(*var)
  end
  def additional_initialize(*var)
    puts "Hello from Mo"
  end
 end

class Foo
  extend Mo
  def initialize
    puts "Hello from Foo"
  end
end

foo = Foo.new

That returns...

Hello from Mo
Hello from Foo

If you're on Ruby 2.0 or later, you can just use prepend. Either require the user to prepend rather than include, or do:

module Mo
  module Initializer
    def initialize
      puts "Hello from Mo#initialize"
      super
    end
  end

  def self.included(klass)
    klass.send :prepend, Initializer
  end
end

Tags:

Ruby