3 ms·
Monkey patching is extremely useful in Ruby but it has to be done with great care. Not having monkey patching available in an OO codebase comes with a lot of he
by brightball 4y ago
Monkey patching is extremely useful in Ruby but it has to be done with great care. Not having monkey patching available in an OO codebase comes with a lot of headaches.
Small example: You're using a 3rd party library that happens to include layers of object inheritance. You notice a piece of functionality a couple of layers up that you need access to or actually requires correction, but wasn't exposed in a way that you can fix it. With monkey patching, you can add a couple of lines of code in your code base that corrects the library without any changes elsewhere. Then you add a test to monitor it to see if something ever changes.
Without monkey patching, you have to fork the entire 3rd party library, make the change, use your fork on your project, keep it up to date and hope the library owner eventually accepts your PR. OR use the code as is and rebuild the inheritance tree in your own code base everywhere it's impacted.
It's indispensable when this scenario comes up.
- JamesSwift 4y agoYep, Ruby has two perfect examples of double-edged swords: monkey patching and 'method missing'. They are both absolutely priceless when leveraged "for good". When leveraged inappropriately however, they can bring the entire thing down. On balance, I love ruby for having the capability to do these things.
- brightball 4y agoYea, I always go to the WAT talk whenever I describe method_missing.