now.to_f
logger.info "Refresh: #{"%.3f" % (end_time-start_time)} s."
retval
end
alias_method :refresh_without_timing, :refresh
alias_method :refresh, :refresh_with_timing
end
We can put this code in a separate file (perhaps alongside other timing code), and, as
long as we require it after the original definition of refresh, the timing code will be
properly added around the original method call. This aids in separation of concerns
because we can separate code into different files based on its functional concern, not
necessarily based on the area that it modifies.
The two alias_method calls patch around the original call to refresh, adding our timing
code. The first call aliases the original method as refresh_without_timing (giving
us a name by which to call the original method from refresh_with_timing); the second
method points refresh at our new method.
This paradigm of using a two alias_method calls to add a feature is common enough
that it has a name in Rails: alias_method_chain. It takes two arguments: the name of
the original method and the name of the feature.
Using alias_method_chain, we can now collapse the two alias_method calls into one
simple line:
alias_method_chain :refresh, :timing
Modulization
Monkeypatching affords us a lot of power, but it pollutes the namespace of the patched
class. Things can often be made cleaner by modulizing the additions and inserting the
module in the class??™s lookup chain.
Pages:
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67