Monkey Patching done in a right way (Have some mercy on legacy Ruby)29 Jan 2011
Classes in Ruby are open; right. That means you can do anything with them, monkey patching around it. But stop doing it before you run into any trouble. I myself used to do it.
Reopening a class to redefine a method that’s been inherited. But it’s wrong as in future you or your colleague might end up asking question to yourself/himself “Why this method is behaving like this”. Because at that time you might or might not aware about that overriding.
Here I am trying to show how we can make it safer.
str.method says it’s coming from MyString; so you might think this method is overridden, But you may not want it. So you try to undefine this method from MyString,
but it does also undefine method inherited from String. That is dangerous. But we would have overcome from this situation if we had did it differently rather rightly.
str.method :empty? points you that this method is coming from a included module
MonkeyPatch::MonkeyString. So we go ahead and remove this method from module
and our good’ol buddy empty? is back again in action.
Have a Happy coding.