Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives to monkey patching core classes

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?

like image 973
dmondark Avatar asked Mar 29 '09 21:03

dmondark


People also ask

Is monkey patching bad?

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.

Is monkey patching metaprogramming?

Metaprogramming. Monkey patching is the first step towards meta-programming - writing code which writes code.

Is Ruby monkey patching States?

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.

What is Monkeypatch Pytest?

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!


1 Answers

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
like image 79
Chuck Avatar answered Oct 19 '22 07:10

Chuck