From: Lars Olsson Date: 2009-09-22T17:45:06+09:00 Subject: Monkeypatching multiple classes with similar methods Hello! I'm trying to monkeypatch a number of related classes that all implements the same method (meth). The methods all take one required argument (stuff) but some of the individual methods may require more arguments (or a block). All I want to do in each call to meth is to print some debug data and then pass the incoming arguments to the original method. This works great as long as I know the exact number of arguments required, but when the number of arguments starts to change my code breaks badly. Is there any way (in ruby 1.8.7) to "copy" the original method signature when defining my own replacement method? /lasso --- CODE START --- class Klass1 def meth(stuff) puts "You've sent #{stuff} to #{self.class}.meth" end end class Klass2 def meth(stuff, &block) block_text = block_given? ? 'with' : 'without' puts "You've sent #{stuff} to #{self.class}.meth #{block_text} a block" end end class Klass3 def meth(stuff, morestuff) puts "You've sent #{stuff} to #{self.class}.meth" end end # Broken monkeypatching. Only works on Klass1 [Klass1, Klass2, Klass3].each do |klass| klass.module_eval do alias_method :original_meth, :meth def meth(stuff) puts "#{self.class}.meth has been patched" original_meth(stuff) end end end Klass1.new.meth('one') Klass2.new.meth('two') { 'three' } # Block is not passed after monkeypatching Klass2.new.meth('four') Klass3.new.meth('five', 'six') # Raises ArgumentError after monkeypatching --- CODE END ---