Top Level Namespace
Instance Method Summary collapse
-
#elapsed(log = nil, good: 'Finished', level: Logger::DEBUG, bad: 'Failed', over: 0) ⇒ 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', over: 0) ⇒ 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
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 53 54 55 56 57 58 59 60 |
# File 'lib/elapsed.rb', line 27 def elapsed(log = nil, good: 'Finished', level: Logger::DEBUG, bad: 'Failed', over: 0) start = Time.now print_it = lambda do |m| duration = Time.now - start return if duration < over m += " in #{start.ago}" if log.nil? puts m elsif level == Logger::DEBUG && log.respond_to?(:debug) log.debug(m) elsif level == Logger::INFO && log.respond_to?(:info) log.info(m) elsif log.respond_to?(:warn) log.warn(m) elsif log.respond_to?(:puts) log.puts(m) else raise "The log doesn't accept any logging requests" 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 |