For the uninitiated, monkeypatching is what you're doing when you add to or alter an existing class. In ruby, you can do things like this:
class C
def func1
# ...
end
end
class C
def func1
# ...
end
def func2
# ...
emd
end
The second "definition" of C lets you define new methods or re-define existing ones. The two need not be in the same source file.
I see "monkeypatching" is "enhancing the implementation of an external class without modifying the supplied source".
If for some reason the functionality provided by some external class or module isn't sufficient for my needs, I need to update or fix it. Sometimes subclassing is an option, but not if you're not the one calling new. In these cases you can modify the existing gem/module, but this could quickly turn into a gem management nightmare. Monkeypatching provides a much more manageable alternative. It has served me well so far.
The key thing to remember when monkeypatching is, are you altering the behavior of a module in a way that could affect other code? If you are just adding methods that don't override methods in base classes (or "created" via method_missing), then only need to worry about the possibility of that method name later being annxed by the module owner. But if you are changing/overriding existing methods, be very careful what you are doing.
And yes, class_eval is essentially the same as wrapping your code in class C and end lines, so it is effectively as "bad" as monkeypatching.
class_eval()does differently? – FrustratedWithFormsDesigner Apr 30 '12 at 20:24class_eval()also lets you monkeypatch a class, I'm guessing the "monkeypatch" is the sole paramter to this function? Maybe usingclass_eval()avoids security issues? – FrustratedWithFormsDesigner Apr 30 '12 at 20:26