class Statum::Machine

Class for representing event machine

@attr_reader [Hash] events Events @attr_reader [Array<Symbol>] states States @attr_reader [Symbol] field State field

Attributes

events[R]
field[R]
name[R]
states[R]

Public Class Methods

new(options) click to toggle source

Creates machine instance

@param [Hash] options options hash @option options [Symbol] field Field to store state @option options [Symbol] initial Initial state @option options [Array<Symbol>] states States @option options [Hash] events Events

# File lib/statum/machine.rb, line 20
def initialize(options)
  @field   = options.delete(:field)
  @initial = options.delete(:initial)
  @states  = options.delete(:states)
  @events  = options.delete(:events)
end

Public Instance Methods

current(instance) click to toggle source

Returns current state of instance

@param [Object] instance Instance of class

@return [Symbol] Current instance's state

# File lib/statum/machine.rb, line 72
def current(instance)
  value = instance.send(field)
  value.nil? ? @initial : value.to_sym
end
event?(name) click to toggle source

Checks if event present

@param [Symbol] name event name

@return [Boolean]

# File lib/statum/machine.rb, line 41
def event?(name)
  @events.keys.include?(name.to_sym)
end
fire!(instance, name) click to toggle source

Execute an event

@param [Object] instance Instance of class, that includes Statum @param [Symbol] name Event name

@raise Statum::UnknownEventError @raise Statum::ErrorTransitionError

# File lib/statum/machine.rb, line 52
def fire!(instance, name)
  raise Statum::UnknownEventError, "Event #{name} not found" unless event?(name)

  current_state = current(instance)
  event         = events[name.to_sym]

  unless event.can_fire?(current_state)
    raise Statum::ErrorTransitionError, "Cannot transition from #{current_state} to #{event.to}"
  end

  event.before.evaluate(instance)
  instance.send("#{field}=", event.to)
  event.after.evaluate(instance)
end
state?(name) click to toggle source

Checks if state present

@param [Symbol] name state name

@return [Boolean]

# File lib/statum/machine.rb, line 32
def state?(name)
  @states.include?(name.to_sym)
end