Introduction
Imagine that you are utilizing a class with a problem in one of its methods. You are aware of the problem and how to resolve it, but you are unable or unwilling to alter the source code.
Solution
From within your program, extend the class and replace the problematic method with a workaround. To still access the flawed version of the technique, create an alias for it.
Suppose we’re trying to use the buggy method in the rexa class defined here:
class rexa
def function(pleasure)
return pleasure * 3 # FIXME: Actually triples your pleasure.
end
end
m = rexa.new
m.function(6) # => 18
Reopen the class, alias the buggy method to another name, and then redefine it with a
correct implementation:
class rexa
alias :function_BUGGY :function
def function(pleasure)
return pleasure * 2
end
end
m.function(6) # => 12
m.function_BUGGY(6) # => 18
A class, function, or method cannot be changed after it has been defined in many programming languages. This action is permissible but discouraged in other languages.
The ability to change classes on the fly is another tool in the arsenal for Ruby programmers to employ as needed. Although adding new code to a class is its most frequent usage, it can also be used to deploy a drop-in replacement for a method's sluggish or defective implementation.
Since Ruby is a purely interpreted language, we should be able to find the source code of any Ruby class used by our program. If a method in one of the classes has a bug, we should be able to copy and paste the original Ruby implementation into our code and fix the bug in the new copy. It's not an efficient technique, but it’s better than distributing a slightly modified version of the entire class or library (that is, copying and pasting a whole file).
You should report your corrections to the software's maintainer in addition to fixing the problematic behavior. The sooner the fix is implemented in your code, the better. You should at least publish the fix online so that others can find it if the software package has been abandoned.
Instead of redefining an existing method if it isn't broken but doesn't do what you want it to, add a new method to the class (or make a subclass). The behavior of the technique may be used by methods you are unaware of.
Of course, there might be techniques that rely on a technique's poor behavior, but that's less likely.