Ruby: Adding things to initialize method through modules Ruby: Adding things to initialize method through modules ruby ruby

Ruby: Adding things to initialize method through modules


There are a few ways you can do this. This example will redefine the initialize method and add whatever extra code you want:

module MyModule  def self.included(base) # built-in Ruby hook for modules    base.class_eval do          original_method = instance_method(:initialize)      define_method(:initialize) do |*args, &block|        original_method.bind(self).call(*args, &block)        @a.push 4 # (your module code here)      end    end  endendclass Test    attr_accessor :a    def initialize      @a = [1, 2, 3]      end    # It must be included after the `initialize`   # definition or the module won't find the method:  include MyModuleend  

However:I think what you really want is subclassing. If you have a lot of classes with similar behavior, as it seems you do, ask yourself if there is a natural abstract parent class. Can you explain what you did with super and why it didn't work?