Class: Charming::Components::Timer

Inherits:
Charming::Component show all
Defined in:
lib/charming/presentation/components/timer.rb

Overview

Timer is a countdown display. Drive it from a controller timer: call tick per interval and check expired? to act when time runs out.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Charming::Component

#captures_text?

Methods inherited from View

#focused?, #layout_assigns

Constructor Details

#initialize(duration:, label: nil, theme: nil) ⇒ Timer

duration is the countdown length in seconds. label is an optional suffix shown after the time.



12
13
14
15
16
17
# File 'lib/charming/presentation/components/timer.rb', line 12

def initialize(duration:, label: nil, theme: nil)
  super(theme: theme)
  @duration = [duration.to_i, 0].max
  @remaining = @duration
  @label = label
end

Instance Attribute Details

#durationObject (readonly)

Returns the value of attribute duration.



8
9
10
# File 'lib/charming/presentation/components/timer.rb', line 8

def duration
  @duration
end

#labelObject (readonly)

Returns the value of attribute label.



8
9
10
# File 'lib/charming/presentation/components/timer.rb', line 8

def label
  @label
end

#remainingObject (readonly)

Returns the value of attribute remaining.



8
9
10
# File 'lib/charming/presentation/components/timer.rb', line 8

def remaining
  @remaining
end

Instance Method Details

#expired?Boolean

True once the countdown has reached zero.

Returns:

  • (Boolean)


26
27
28
# File 'lib/charming/presentation/components/timer.rb', line 26

def expired?
  remaining.zero?
end

#renderObject

Renders the remaining time (with the label appended when present).



37
38
39
40
# File 'lib/charming/presentation/components/timer.rb', line 37

def render
  clock = TimeDisplay.clock(remaining)
  label ? "#{clock} #{label}" : clock
end

#resetObject

Restores the full duration. Returns self.



31
32
33
34
# File 'lib/charming/presentation/components/timer.rb', line 31

def reset
  @remaining = duration
  self
end

#tick(seconds = 1) ⇒ Object

Counts down by seconds (default 1), clamping at zero. Returns self.



20
21
22
23
# File 'lib/charming/presentation/components/timer.rb', line 20

def tick(seconds = 1)
  @remaining = [@remaining - seconds, 0].max
  self
end