Using define_method to overwrite a class' initialize as an example of overwriting a method from your mock, version 2 1

Posted by Tim Connor Fri, 30 Nov 2007 22:40:00 GMT

Last year, I wrote an article about redefining an instance method from a module via alias_method. I understand better how extend/include work together now (and the ClassMethods include patterns and whatnot) so I am little embarrassed at my earlier confusion, but there is one concrete thing I wanted to add/simplify.

If you are mocking and don’t need to keep a reference to the old method, using define_method might be marginally cleaner.

def self.included(associator_class) 
  associator_class.send(:define_method, :initialize, instance_method(:initialize))

This is handier because you can skip the method definition/reference logic and just do it in situ, for instant-stubification

ClassToBeIntercepted.send :define_method, :method_to_be_nuked, proc {return ’nuked’}


Leave a comment

  1. Avatar
    Tim Connor 41 minutes later:

    Of course, depending on how hacky your stub is, you might want to keep an old reference separately with an alias_method call first, and then realias it back when you are done.