class Clock
A simple clock that tracks elapsed time with start, pause, resume, and reset.
The clock accumulates elapsed time while running and freezes it when paused.
Definitions
def initialize
Initialize a new clock in the stopped state.
Implementation
def initialize
@elapsed = 0
@started = false
@running = false
@last_tick = nil
end
def started?
Whether the clock has been started at least once.
Signature
-
returns
Boolean
Implementation
def started?
@started
end
def running?
Whether the clock is currently running and accumulating time.
Signature
-
returns
Boolean
Implementation
def running?
@running
end
def paused?
Whether the clock has been started but is currently paused.
Signature
-
returns
Boolean
Implementation
def paused?
started? && !@running
end
def elapsed
The total elapsed time in seconds. Includes time accumulated up to now if running, or frozen time if paused.
Signature
-
returns
Numeric The elapsed time in seconds.
Implementation
def elapsed
if @running
@elapsed + (Time.now - @last_tick)
else
@elapsed
end
end
def start!
Start the clock. Begins accumulating time from now.
Implementation
def start!
@started = true
@running = true
@last_tick = Time.now
end
def restore!(elapsed, running:)
Directly restore the clock to a previously persisted state.
Signature
-
parameter
elapsedNumeric The elapsed time to restore.
-
parameter
runningBoolean Whether the clock should resume running.
Implementation
def restore!(elapsed, running:)
@started = true
@elapsed = elapsed
@running = running
@last_tick = running ? Time.now : nil
end
def pause!
Pause the clock. Freezes the elapsed time at the current value.
Implementation
def pause!
return unless @running
@elapsed += Time.now - @last_tick
@running = false
end
def resume!
Resume the clock after a pause. Continues accumulating time from now.
Implementation
def resume!
return if @running
@running = true
@last_tick = Time.now
end
def reset!(elapsed = 0)
Reset the elapsed time to the given value. If running, continues from the new value. If paused, sets the frozen value.
Signature
-
parameter
elapsedNumeric The new elapsed time in seconds.
Implementation
def reset!(elapsed = 0)
@elapsed = elapsed
@last_tick = Time.now if @running
end