Class: Presently::Clock
- Inherits:
-
Object
- Object
- Presently::Clock
- Defined in:
- lib/presently/clock.rb
Overview
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.
Instance Method Summary collapse
-
#elapsed ⇒ Object
The total elapsed time in seconds.
-
#initialize ⇒ Clock
constructor
Initialize a new clock in the stopped state.
-
#pause! ⇒ Object
Pause the clock.
-
#paused? ⇒ Boolean
Whether the clock has been started but is currently paused.
-
#reset!(elapsed = 0) ⇒ Object
Reset the elapsed time to the given value.
-
#resume! ⇒ Object
Resume the clock after a pause.
-
#running? ⇒ Boolean
Whether the clock is currently running and accumulating time.
-
#start! ⇒ Object
Start the clock.
-
#started? ⇒ Boolean
Whether the clock has been started at least once.
Constructor Details
#initialize ⇒ Clock
Initialize a new clock in the stopped state.
12 13 14 15 16 |
# File 'lib/presently/clock.rb', line 12 def initialize @elapsed = 0 @running = false @last_tick = nil end |
Instance Method Details
#elapsed ⇒ Object
The total elapsed time in seconds. Includes time accumulated up to now if running, or frozen time if paused.
39 40 41 42 43 44 45 |
# File 'lib/presently/clock.rb', line 39 def elapsed if @running @elapsed + (Time.now - @last_tick) else @elapsed end end |
#pause! ⇒ Object
Pause the clock. Freezes the elapsed time at the current value.
54 55 56 57 58 59 |
# File 'lib/presently/clock.rb', line 54 def pause! return unless @running @elapsed += Time.now - @last_tick @running = false end |
#paused? ⇒ Boolean
Whether the clock has been started but is currently paused.
32 33 34 |
# File 'lib/presently/clock.rb', line 32 def paused? started? && !@running end |
#reset!(elapsed = 0) ⇒ Object
Reset the elapsed time to the given value. If running, continues from the new value. If paused, sets the frozen value.
72 73 74 75 |
# File 'lib/presently/clock.rb', line 72 def reset!(elapsed = 0) @elapsed = elapsed @last_tick = Time.now if @running end |
#resume! ⇒ Object
Resume the clock after a pause. Continues accumulating time from now.
62 63 64 65 66 67 |
# File 'lib/presently/clock.rb', line 62 def resume! return if @running @running = true @last_tick = Time.now end |
#running? ⇒ Boolean
Whether the clock is currently running and accumulating time.
26 27 28 |
# File 'lib/presently/clock.rb', line 26 def running? @running end |
#start! ⇒ Object
Start the clock. Begins accumulating time from now.
48 49 50 51 |
# File 'lib/presently/clock.rb', line 48 def start! @running = true @last_tick = Time.now end |
#started? ⇒ Boolean
Whether the clock has been started at least once.
20 21 22 |
# File 'lib/presently/clock.rb', line 20 def started? !@last_tick.nil? end |