Opening classes and
adding code is referred to as monkeypatching (a term from the Python community).
Though it sounds derogatory, this term is used in a decidedly positive light; monkeypatching
is, on the whole, seen as an incredibly useful technique. Almost all Rails
plugins monkeypatch the Rails core in some way or another.
Disadvantages of monkeypatching
There are two primary disadvantages to monkeypatching. First, the code for one
method call may be spread over several files. The foremost example of this is in
ActionController??™s process method. This method is intercepted by methods in up to
five different files during the course of a request. Each of these methods adds another
feature: filters, exception rescue, components, and session management. The end
result is a net gain: the benefit gained by separating each functional component into
a separate file outweighs the inflated call stack.
32 | Chapter 1: Foundational Techniques
Another consequence of the functionality being spread around is that it can be difficult
to properly document a method. Because the function of the process method
can change depending on which code has been loaded, there is no good place to document
what each of the methods is adding. This problem exists because the actual
identity of the process method changes as the methods are chained together.
Adding Functionality to Existing Methods
Because Rails encourages the philosophy of separation of concerns, you often will
have the need to extend the functionality of existing code.
Pages:
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63