Class: Statum::Machine
- Inherits:
-
Object
- Object
- Statum::Machine
- Defined in:
- lib/statum/machine.rb
Overview
Class for representing event machine
Instance Attribute Summary collapse
-
#events ⇒ Object
readonly
Returns the value of attribute events.
-
#field ⇒ Object
(also: #name)
readonly
Returns the value of attribute field.
-
#states ⇒ Object
readonly
Returns the value of attribute states.
Instance Method Summary collapse
-
#current(instance) ⇒ Symbol
Returns current state of instance.
-
#event?(name) ⇒ Boolean
Checks if event present.
-
#fire!(instance, name) ⇒ Object
Execute an event.
-
#initialize(options) ⇒ Machine
constructor
Creates machine instance.
-
#state?(name) ⇒ Boolean
Checks if state present.
Constructor Details
#initialize(options) ⇒ Machine
Creates machine instance
12 13 14 15 16 17 |
# File 'lib/statum/machine.rb', line 12 def initialize() @field = .delete(:field) @initial = .delete(:initial) @states = .delete(:states) @events = .delete(:events) end |
Instance Attribute Details
#events ⇒ Object (readonly)
Returns the value of attribute events.
4 5 6 |
# File 'lib/statum/machine.rb', line 4 def events @events end |
#field ⇒ Object (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 |
#states ⇒ Object (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
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
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
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
24 25 26 |
# File 'lib/statum/machine.rb', line 24 def state?(name) @states.include?(name.to_sym) end |