PresentlySourcePresentlyState

class State

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.

Definitions

DEFAULT_PATH = ".presently.json"

The default state file path.

def initialize(path = DEFAULT_PATH)

Initialize a new state instance.

Signature

parameter path String

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 controller PresentationController

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 controller PresentationController

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])
	end
rescue => error
	Console.warn(self, "Failed to restore state", exception: error)
end