now.to_f
returning(self.send(:"#{method}_without_timing")) do
end_time = Time.now.to_f
* This code sample uses variable interpolation inside a symbol literal. Because the symbol is defined using a
double-quoted string, variable interpolation is just as valid as in any other double-quoted string: the symbol
:"sym#{2+2}" is the same symbol as :sym4.
42 | Chapter 1: Foundational Techniques
puts "#{method}: #{"%.3f" % (end_time-start_time)} s."
end
end
end
end
We add singleton methods to Person to enable or disable tracing:
class << Person
def start_trace
TIMED_METHODS.each do |method|
alias_method method, :"#{method}_with_timing"
end
end
def end_trace
TIMED_METHODS.each do |method|
alias_method method, :"#{method}_without_timing"
end
end
end
To enable tracing, we wrap each method call in the timed method call. To disable it,
we simply point the method call back to the original method (which is now only
accessible by its _without_timing alias).
To use these additions, we simply call the Person.trace method:
p = Person.new
p.refresh # => (...)
Person.start_trace
p.refresh # => (...)
# -> refresh: 0.500 s.
Person.end_trace
p.refresh # => (...)
Now that we have the ability to add and remove the timing code during execution,
we can expose this through our application; we could give the administrator or
developer an interface to trace all or specified functions without restarting the application.
Pages:
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76