Class: Statum::Machine

Inherits:
Object
  • Object
show all
Defined in:
lib/statum/machine.rb

Overview

Class for representing event machine

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Machine

Creates machine instance

Parameters:

  • options (Hash)

    options hash



12
13
14
15
16
17
# File 'lib/statum/machine.rb', line 12

def initialize(options)
  @field   = options.delete(:field)
  @initial = options.delete(:initial)
  @states  = options.delete(:states)
  @events  = options.delete(:events)
end

Instance Attribute Details

#eventsObject (readonly)

Returns the value of attribute events.



4
5
6
# File 'lib/statum/machine.rb', line 4

def events
  @events
end

#fieldObject (readonly) Also known as: name

Returns the value of attribute field.



4
5
6
# File 'lib/statum/machine.rb', line 4

def field
  @field
end

#statesObject (readonly)

Returns the value of attribute states.



4
5
6
# File 'lib/statum/machine.rb', line 4

def states
  @states
end

Instance Method Details

#current(instance) ⇒ Symbol

Returns current state of instance

Parameters:

  • instance (Object)

    Instance of class

Returns:

  • (Symbol)

    Current instance’s state



61
62
63
64
# File 'lib/statum/machine.rb', line 61

def current(instance)
  value = instance.send(field)
  value.nil? ? @initial : value.to_sym
end

#event?(name) ⇒ Boolean

Checks if event present

Parameters:

  • name (String|Boolean)

    event name

Returns:

  • (Boolean)


33
34
35
# File 'lib/statum/machine.rb', line 33

def event?(name)
  @events.keys.include?(name.to_sym)
end

#fire!(instance, name) ⇒ Object

Execute an event

Parameters:

  • instance (Object)

    Instance of class, that includes Statum

  • name (String|Symbol)

    Event name

Raises:



41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/statum/machine.rb', line 41

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) ⇒ Boolean

Checks if state present

Parameters:

  • name (String|Symbol)

    state name

Returns:

  • (Boolean)


24
25
26
# File 'lib/statum/machine.rb', line 24

def state?(name)
  @states.include?(name.to_sym)
end