class State
Persists and restores presentation controller state to/from a JSON file.
Tracks the current slide index, clock elapsed time, and whether it is ready, running, or paused. This allows the presentation to survive server restarts without losing position.
Definitions
DEFAULT_PATH = ".presently.json"
The default state file path.
def initialize(path = DEFAULT_PATH)
Initialize a new state instance.
Signature
-
parameter
pathString The file path for the state file.
Implementation
def initialize(path = DEFAULT_PATH)
@path = path
end
attr :path
Signature
-
attribute
String The file path for the state file.
def save(controller)
Save the controller's current state to disk.
Signature
-
parameter
controllerPresentationController The controller to save.
Implementation
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
def restore(controller)
Restore persisted state into the given controller.
Signature
-
parameter
controllerPresentationController The controller to restore into.
Implementation
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])
else
controller.clock.reset!(data[:elapsed].to_f, started: false)
end
rescue => error
Console.warn(self, "Failed to restore state", exception: error)
end