I am still new to Ruby and basically just writing my first micro-program after finishing Cooper's book. I was pointed to the direction of avoiding monkey patching but the problem is I don't know what are the alternatives to achieve the same behavior. Basically, I want to add a new method that is accessible by every string object. The obvious monkey-patching way is to:
class String
def do_magic
...magic...
end
end
I recall there's a way using String.send. But I can't remember how it's done nor where I read it. Can anyone point out any alternatives that would still let me make that method available to the String class and child objects?
But you should never consider this a standard technique and build monkey patch upon monkey patch. This is considered bad because it means that an object's definition does not completely or accurately describe how it actually behaves.
Metaprogramming. Monkey patching is the first step towards meta-programming - writing code which writes code.
In Ruby, a Monkey Patch (MP) is referred to as a dynamic modification to a class and by a dynamic modification to a class means to add new or overwrite existing methods at runtime. This ability is provided by ruby to give more flexibility to the coders.
monkeypatch is a part of the pytest-mock library that allows you to intercept what a function would normally do, substituting its full execution with a return value of your own specification. Note that monkey patching a function call does not count as actually testing that function call!
Any other way of doing this would just be a more awkward syntax for monkey patching. There are ways involving send
and eval
and all sorts of things, but why? Go ahead and do it the obvious way.
You want to be careful of monkey patching in big projects or when you have dependencies, because you can wind up with conflicts when several hands are all messing around in the same place. This doesn't mean look for an alternative syntax that accomplishes the same thing — it means be careful when you're making changes that could affect code that's not yours. This probably isn't a concern in your particular case. It's just something that might need to be addressed in larger projects.
One alternative in Ruby is that you can add methods to a single object.
a = "Hello"
b = "Goodbye"
class <<a
def to_slang
"yo"
end
end
a.to_slang # => "yo"
b.to_slang # NoMethodError: undefined method `to_slang' for "Goodbye":String
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With