Module: RubySmart::SimpleLogger::Extensions::Timer

Included in:
Logger
Defined in:
lib/ruby_smart/simple_logger/extensions/timer.rb

Instance Method Summary collapse

Instance Method Details

#timer(action, key = :default, opts = {}) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
53
54
55
56
57
58
59
60
61
# File 'lib/ruby_smart/simple_logger/extensions/timer.rb', line 7

def timer(action, key = :default, opts = {})
  return if key.nil?

  @timers      ||= {}
  @timers[key] ||= {
    start:   nil,
    stop:    nil,
    total: 0
  }

  case action
  when :start, :restart
    @timers[key][:start]   = Time.now
    @timers[key][:stop]    = nil
    @timers[key][:total] = 0

    true
  when :continue
    @timers[key][:start] = Time.now
    @timers[key][:stop]  = nil

    true
  when :stop
    return false if !@timers[key][:start] || @timers[key][:stop]
    @timers[key][:stop]    = Time.now
    @timers[key][:total] += @timers[key][:stop] - @timers[key][:start]

    true
  when :pause
    return false if !@timers[key][:start] || @timers[key][:stop]

    @timers[key][:total] += Time.now - @timers[key][:start]
    @timers[key][:start]   = nil
    @timers[key][:stop]    = nil

    true
  when :clear
    self.timer(:stop, key)
    current = self.timer(:current, key)
    @timers.delete(key)

    # time_ago_in_words in only available if activesupport & actionview gems are loaded
    if opts[:humanized] && respond_to?(:time_ago_in_words)
      time_ago_in_words(current.to_i.seconds.from_now, include_seconds: true)
    else
      current
    end
  when :current
    current = @timers[key][:total]
    current += Time.now - @timers[key][:start] if @timers[key][:start] && @timers[key][:stop].nil?
    current
  else
    nil
  end
end