Class: Jsm::Event

Inherits:
Object
  • Object
show all
Defined in:
lib/jsm/event.rb

Overview

Jsm::Event handle event related task registered by the main module. It do transition process from one state to another state

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, params = {}, &block) ⇒ Event

Returns a new instance of Event.



13
14
15
16
17
18
# File 'lib/jsm/event.rb', line 13

def initialize(name, params = {}, &block)
  @name = name
  @states = params[:states]
  @transitions = []
  instance_eval(&block) if block_given?
end

Instance Attribute Details

#attribute_nameObject

Returns the value of attribute attribute_name.



5
6
7
# File 'lib/jsm/event.rb', line 5

def attribute_name
  @attribute_name
end

#nameObject (readonly)

Returns the value of attribute name.



4
5
6
# File 'lib/jsm/event.rb', line 4

def name
  @name
end

#statesObject (readonly)

Returns the value of attribute states.



4
5
6
# File 'lib/jsm/event.rb', line 4

def states
  @states
end

#transitionsObject (readonly)

Returns the value of attribute transitions.



4
5
6
# File 'lib/jsm/event.rb', line 4

def transitions
  @transitions
end

Instance Method Details

#can_be_executed?(object) ⇒ Boolean

method to check whether this event can be executed

Returns:

  • (Boolean)


53
54
55
56
# File 'lib/jsm/event.rb', line 53

def can_be_executed?(object)
  from_states = transitions.map(&:from).flatten
  from_states.include?(object.current_state)
end

#can_be_transitioning_to(object) ⇒ Object

check when running this event, which transitions can change the state of object state return the transition object



48
49
50
# File 'lib/jsm/event.rb', line 48

def can_be_transitioning_to(object)
  transitions.find{ |transition| transition.from.include?(obj_state(object)) }
end

#execute(object) ⇒ Object

execute the event, and do a transition if the object current state match with the from state of a transition



36
37
38
39
40
41
42
43
44
# File 'lib/jsm/event.rb', line 36

def execute(object)
  transition = can_be_transitioning_to(object)
  if transition
    change_state_obj(object, transition.to)
    true
  else
    false
  end
end

#transition(params = {}) ⇒ Object

register a transition into the. When Event is executed, these transitions is transitioning an object into ‘to` state, if their current state match with one of the `from` state. the argument input is params `from` and params `to`. Both params should be exist



25
26
27
28
29
30
31
# File 'lib/jsm/event.rb', line 25

def transition(params = {})
  validate_params(params)
  validate_state_transition(params)
  from = params[:from].is_a?(Array) ? params[:from] : [params[:from]]
  transition = Jsm::Transition.new(from, params[:to])
  @transitions.push(transition)
end