module Ably::Modules::StateEmitter

StateEmitter module adds a set of generic state related methods to a class on the assumption that the instance variable @state is used exclusively, the {Enum} STATE is defined prior to inclusion of this module, and the class is an {EventEmitter}. It then emits state changes.

It also ensures the EventEmitter is configured to restrict permitted events to the the available STATEs or EVENTs if defined i.e. if EVENTs includes an additional type such as :update, then it will support all EVENTs being emitted. EVENTs must be a superset of STATEs

@note This module requires that the method logger is defined.

@example

class Connection
  include Ably::Modules::EventEmitter
  extend  Ably::Modules::Enum
  STATE = ruby_enum('STATE',
    :initialized,
    :connecting,
    :connected
  )
  include Ably::Modules::StateEmitter
end

connection = Connection.new
connection.state = :connecting     # emits :connecting event via EventEmitter, returns STATE.Connecting
connection.state?(:connected)      # => false
connection.connecting?             # => true
connection.state                   # => STATE.Connecting
connection.state = :invalid        # raises an Exception as only a valid state can be defined
connection.emit :invalid           # raises an Exception as only a valid state can be used for EventEmitter
connection.change_state :connected # emits :connected event via EventEmitter, returns STATE.Connected
connection.once_or_if(:connected) { puts 'block called once when state is connected or becomes connected' }