class Clock

A simple clock that tracks elapsed time with start, pause, resume, and reset.

A ready clock waits to start at its current elapsed time. It accumulates time while running and freezes it when paused.

Definitions

def initialize

Initialize a new clock in the ready state at zero.

Implementation

def initialize
	@elapsed = 0
	@started = false
	@running = false
	@last_tick = nil
end

def started?

Whether the clock is running or paused; false when ready.

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 or ready.

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 elapsed Numeric

The elapsed time to restore.

parameter running Boolean

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 = nil, started: !elapsed.nil?)

Reset the clock to its initial, ready state, or set its elapsed time. A numeric value preserves whether the clock is running; a ready clock becomes paused. Pass started: false to make the clock ready at the given elapsed time.

Signature

parameter elapsed Numeric | Nil

The elapsed time in seconds, or nil to clear the clock.

parameter started Boolean

Whether the clock is running or paused at the reset position; false makes it ready.

Implementation

def reset!(elapsed = nil, started: !elapsed.nil?)
	@elapsed = elapsed || 0
	@started = started
	@running = @started && @running
	@last_tick = @running ? Time.now : nil
end