Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

42 | Chapter 1: Foundational Techniques


puts "#{method}: #{"%.3f" % (end_time-start_time)} s."
end
end
end
end

We add singleton methods toPerson 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 thePerson.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 appli-
cation. This approach has several advantages over adding logging code to each func-
tion separately:



  • The original code is untouched; it can be changed or upgraded without affecting
    the tracing code.

  • When tracing is disabled, the code performs exactly as it did before tracing; the
    tracing code is invisible in stack traces. There is no performance overhead when
    tracing is disabled.

Free download pdf