From 76edeac34aad174d4ff3b11eb79031ab96201f28 Mon Sep 17 00:00:00 2001 From: Gavin Laking Date: Fri, 29 Jan 2016 00:24:50 +0000 Subject: [PATCH] Do not measure timing if debugging is disabled or no block of code was given. --- lib/vedeu/logging/timer.rb | 26 +++++++++++++++++--------- test/lib/vedeu/logging/timer_test.rb | 12 +++++++++++- 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/lib/vedeu/logging/timer.rb b/lib/vedeu/logging/timer.rb index d99045ab8..23100849d 100644 --- a/lib/vedeu/logging/timer.rb +++ b/lib/vedeu/logging/timer.rb @@ -33,24 +33,30 @@ def initialize(message = '') end # Write an entry to the log file stating how long a section of - # code took in milliseconds. Useful for debugging performance. + # code took in milliseconds when debugging is enabled and a + # block was Useful for debugging performance. # # @param block [Proc] # @macro raise_requires_block - # @return [void] The return value of the executed block. + # @return [void|NilClass] The return value of the executed + # block if given, or nil if debugging is disabled. def measure(&block) - fail Vedeu::Error::RequiresBlock unless block_given? + if block_given? + if Vedeu.config.debug? + work = yield - if Vedeu.config.debug? - work = yield + Vedeu.log(type: :timer, + message: "#{message} took #{elapsed}ms.") - Vedeu.log(type: :timer, - message: "#{message} took #{elapsed}ms.") + work - work + else + yield + + end else - yield + fail Vedeu::Error::RequiresBlock if Vedeu.config.debug? end end @@ -65,6 +71,8 @@ def measure(&block) # @return [String] attr_reader :message + private + # Returns the elapsed time in milliseconds with 3 decimal # places. # diff --git a/test/lib/vedeu/logging/timer_test.rb b/test/lib/vedeu/logging/timer_test.rb index 048a9734b..5a91bb2ff 100644 --- a/test/lib/vedeu/logging/timer_test.rb +++ b/test/lib/vedeu/logging/timer_test.rb @@ -51,7 +51,17 @@ module Logging context 'when the block is not given' do subject { instance.measure } - it { proc { subject }.must_raise(Vedeu::Error::RequiresBlock) } + context 'when debugging is enabled' do + before { Vedeu.config.stubs(:debug?).returns(true) } + + it { proc { subject }.must_raise(Vedeu::Error::RequiresBlock) } + end + + context 'when debugging is disabled' do + before { Vedeu.config.stubs(:debug?).returns(false) } + + it { subject.must_equal(nil) } + end end end