This post originated from an RSS feed registered with Ruby Buzz
by Jay Fields.
Original Post: Ruby: Move a Method From a Class to a Module Definition
Feed Title: Jay Fields Thoughts
Feed URL: http://feeds.feedburner.com/jayfields/mjKQ
Feed Description: Blog about Ruby, Agile, Testing and other topics related to software development.
I was recently working with a framework that reopened and defined a method on Object. I wanted the behavior of the framework, but I also wanted to define my own behavior. This is generally the case for alias_method_chain or one of the other Alternatives for Redefining Methods, but my circumstances (to be discussed in a subsequent post) prevented me from using one of the better known solutions.
The solution that worked for me was to move the original method definition to a module.
classSpeaker defsay_hello "hello" end end
moduleEnglishSpeaker expects_method =Speaker.instance_method(:say_hello) define_method :say_hellodo |*args| expects_method.bind(self).call(*args) end end
You may never need this technique, I only needed it once in the past 2.5 years. But, when it applied I found it to be significantly better than the alternatives.