Class: Presently::State
- Inherits:
-
Object
- Object
- Presently::State
- Defined in:
- lib/presently/state.rb
Overview
Persists and restores presentation controller state to/from a JSON file.
Tracks the current slide index, clock elapsed time, and clock running state. This allows the presentation to survive server restarts without losing position.
Constant Summary collapse
- DEFAULT_PATH =
The default state file path.
".presently.json"
Instance Attribute Summary collapse
-
#path ⇒ Object
readonly
Returns the value of attribute path.
- #The file path for the state file.(filepath) ⇒ Object readonly
Instance Method Summary collapse
-
#initialize(path = DEFAULT_PATH) ⇒ State
constructor
Initialize a new state instance.
-
#restore(controller) ⇒ Object
Restore persisted state into the given controller.
-
#save(controller) ⇒ Object
Save the controller’s current state to disk.
Constructor Details
#initialize(path = DEFAULT_PATH) ⇒ State
Initialize a new state instance.
19 20 21 |
# File 'lib/presently/state.rb', line 19 def initialize(path = DEFAULT_PATH) @path = path end |
Instance Attribute Details
#path ⇒ Object (readonly)
Returns the value of attribute path.
24 25 26 |
# File 'lib/presently/state.rb', line 24 def path @path end |
#The file path for the state file.(filepath) ⇒ Object (readonly)
24 |
# File 'lib/presently/state.rb', line 24 attr :path |
Instance Method Details
#restore(controller) ⇒ Object
Restore persisted state into the given controller.
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/presently/state.rb', line 43 def restore(controller) return unless File.exist?(@path) data = JSON.parse(File.read(@path), symbolize_names: true) # Restore slide position: if index = data[:current_index] controller.go_to(index.to_i) end # Restore clock state: if data[:started] controller.clock.restore!(data[:elapsed].to_f, running: data[:running]) end rescue => error Console.warn(self, "Failed to restore state", exception: error) end |
#save(controller) ⇒ Object
Save the controller’s current state to disk.
28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/presently/state.rb', line 28 def save(controller) data = { current_index: controller.current_index, elapsed: controller.clock.elapsed, running: controller.clock.running?, started: controller.clock.started?, } File.write(@path, JSON.pretty_generate(data)) rescue => error Console.warn(self, "Failed to save state", exception: error) end |