Top Level Namespace
Instance Method Summary collapse
-
#elapsed(log = nil, good: 'Finished', level: Logger::DEBUG, bad: 'Failed') ⇒ Object
The function measures the time taken by a block to execute and then prints it to the log.
Instance Method Details
#elapsed(log = nil, good: 'Finished', level: Logger::DEBUG, bad: 'Failed') ⇒ Object
The function measures the time taken by a block to execute and then prints it to the log.
require 'elapsed'
elapsed(log) do
do_something_slow
throw 'It was completed'
end
- Author
-
Yegor Bugayenko ([email protected])
- Copyright
-
Copyright © 2024-2025 Yegor Bugayenko
- License
-
MIT
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/elapsed.rb', line 26 def elapsed(log = nil, good: 'Finished', level: Logger::DEBUG, bad: 'Failed') start = Time.now print_it = lambda do |m| m += " in #{start.ago}" if log.nil? puts m elsif level == Logger::DEBUG log.debug(m) elsif level == Logger::INFO log.info(m) else log.warn(m) end end begin ret = yield print_it.call(good.to_s) ret rescue UncaughtThrowError => e tag = e.tag throw e unless tag.is_a?(Symbol) print_it.call(tag.to_s) rescue StandardError => e print_it.call(bad.to_s) raise e end end |