State

A driver should be built to represent the state of the device or service it is abstracting.

  • User interfaces can bind to state to provide visual feedback

  • Logic can query state and subscribe to state changes to trigger further actions

  • Any authenticated user can read the state

  • Do not store sensitive material in state

Exposing State

A driver quacks like a hash

All state keys must be Symbols, Strings or respond to #to_sym

  • Setting state self[:state_key] = 'value'

  • Reading state self[:stafe_key] # => 'value'

Logic can access driver state in the same way

  • Reading state system[:Display][:power] # => true

  • Setting state system[:Display][:not_recommended] = true

Logic might trigger a useful action by changing the state of other drivers directly, however generally it is recommended to use a mutator method.

  • JSON compatible classes: nil, true, false, Hash, String, Integer, Array, Float, Symbol

  • Objects that respond to: #to_json or failing that #to_s will be called when sending over the API

  • Objects that don’t meet these requirements can be used server side and are sent as nil over the API

Subscribing to State

All drivers can subscribe to their own state.

Logic can additionally subscribe to state of other drivers.

Change detection

When state is applied it is checked against the existing value and subscribers are only notified if the value has changed.

Change detection doesn’t work if you mutate a variable.

The recommended method for updating complex state is:

  1. Duplicate my_array = ['my', 'array'].dup or {complex:['hash']}.deep_dup

    • .deep_dup when in doubt

  2. Update my_array << 8

  3. Apply self[:my_array] = my_array

This can be achieved by using operations that create a new object

Last updated

Was this helpful?