Class: Jsm::Base

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

Overview

this module used as extension for state machine class The DSL is built to define the state, event, and transition that happen

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass) ⇒ Base

Returns a new instance of Base.



79
80
81
82
# File 'lib/jsm/base.rb', line 79

def initialize(klass)
  @klass = klass
  Jsm::ClientExtension.decorate(@klass, state_machine: self.class)
end

Class Method Details

.attribute_name(attribute_name = nil) ⇒ Object

define attribute name of state attribute in the client class



6
7
8
9
10
11
12
# File 'lib/jsm/base.rb', line 6

def self.attribute_name(attribute_name = nil)
  if attribute_name.nil?
    @attribute_name
  else
    @attribute_name = attribute_name
  end
end

.event(name, &block) ⇒ Object

add new event to the class and add its transition example: event :do_this do transition from: :x, to: :y transition from: [:j, :g], to: :z



45
46
47
48
49
50
51
52
# File 'lib/jsm/base.rb', line 45

def self.event(name, &block)
  @events ||= {}
  if !@events[name].nil?
    raise Jsm::InvalidEventError, "event #{name} has been registered"
  end

  @events[name] = Jsm::Event.new(name, states: @states, &block)
end

.eventsObject

get list of all events



55
56
57
# File 'lib/jsm/base.rb', line 55

def self.events
  @events
end

.initial_stateObject

return initial_state if empty return nil



34
35
36
37
38
# File 'lib/jsm/base.rb', line 34

def self.initial_state
  if @states
   @states.initial_state
 end
end

.state(name, params = {}) ⇒ Object

add new state to class example state :x state :y if put params initial true it will be treated as initial_state example: state :x, initial: true



22
23
24
25
# File 'lib/jsm/base.rb', line 22

def self.state(name, params = {})
  @states ||= Jsm::States.new
  @states.add_state(name, initial: params[:initial])
end

.statesObject

list of all states



28
29
30
# File 'lib/jsm/base.rb', line 28

def self.states
  @states.list
end

.validate(state_name, &block) ⇒ Object

add validation of a state(when changes to the targeted state, check whether passed this validation or not) example: state :y validate :y do |obj|

obj.name == 'testMe'

end



65
66
67
68
69
70
71
72
# File 'lib/jsm/base.rb', line 65

def self.validate(state_name, &block)
  unless @states.has_state?(state_name)
    raise Jsm::InvalidStateError, "there is no state y"
  end

  @validators ||= Jsm::Validators.new
  @validators.add_validator(state_name, Jsm::Validator.new(:state, state_name, &block))
end

.validatorsObject

list all validators that exist



75
76
77
# File 'lib/jsm/base.rb', line 75

def self.validators
  @validators
end