Class: Timer

Inherits:
Object
  • Object
show all
Defined in:
lib/esm/extension/timer.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTimer

Returns a new instance of Timer.



25
26
27
28
# File 'lib/esm/extension/timer.rb', line 25

def initialize
  @started_at = nil
  @stopped_at = nil
end

Instance Attribute Details

#started_atObject (readonly)

Returns the value of attribute started_at.



4
5
6
# File 'lib/esm/extension/timer.rb', line 4

def started_at
  @started_at
end

#stopped_atObject (readonly)

Returns the value of attribute stopped_at.



4
5
6
# File 'lib/esm/extension/timer.rb', line 4

def stopped_at
  @stopped_at
end

Class Method Details

.start!Object



21
22
23
# File 'lib/esm/extension/timer.rb', line 21

def self.start!
  new.start!
end

.time(&block) ⇒ Integer

Runs the provided block with a timer

Returns:

  • (Integer)

    The elapsed time in seconds



11
12
13
14
15
16
17
18
19
# File 'lib/esm/extension/timer.rb', line 11

def self.time(&block)
  timer = new

  timer.start!
  yield
  timer.stop!

  timer.time_elapsed
end

Instance Method Details

#finished?Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/esm/extension/timer.rb', line 52

def finished?
  !stopped_at.nil?
end

#reset!Object



42
43
44
45
46
# File 'lib/esm/extension/timer.rb', line 42

def reset!
  @started_at = nil
  @stopped_at = nil
  self
end

#start!Object



30
31
32
33
# File 'lib/esm/extension/timer.rb', line 30

def start!
  @started_at ||= Time.current
  self
end

#started?Boolean

Returns:

  • (Boolean)


48
49
50
# File 'lib/esm/extension/timer.rb', line 48

def started?
  !started_at.nil?
end

#stop!Object



35
36
37
38
39
40
# File 'lib/esm/extension/timer.rb', line 35

def stop!
  return self if @started_at.nil?

  @stopped_at ||= Time.current
  time_elapsed
end

#time_elapsedObject



56
57
58
59
60
# File 'lib/esm/extension/timer.rb', line 56

def time_elapsed
  return 0 if started_at.nil?

  (stopped_at || Time.current) - started_at
end

#to_hObject



62
63
64
65
66
67
68
# File 'lib/esm/extension/timer.rb', line 62

def to_h
  {
    started_at: started_at,
    stopped_at: stopped_at,
    time_elapsed: time_elapsed
  }
end