Module: StatePattern

Defined in:
lib/state_pattern.rb,
lib/state_pattern/state.rb,
lib/state_pattern/invalid_transition_exception.rb

Defined Under Namespace

Modules: ClassMethods Classes: InvalidTransitionException, State

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#current_eventObject

Returns the value of attribute current_event.



58
59
60
# File 'lib/state_pattern.rb', line 58

def current_event
  @current_event
end

#current_stateObject

Returns the value of attribute current_state.



58
59
60
# File 'lib/state_pattern.rb', line 58

def current_state
  @current_state
end

Class Method Details

.included(base) ⇒ Object



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

def self.included(base)
  base.extend ClassMethods
end

Instance Method Details

#delegate_to_event(method_name, *args) ⇒ Object



69
70
71
72
# File 'lib/state_pattern.rb', line 69

def delegate_to_event(method_name, *args)
  self.current_event = method_name.to_sym
  self.current_state.send(current_event, *args)
end

#initialize(*args) ⇒ Object



59
60
61
62
63
# File 'lib/state_pattern.rb', line 59

def initialize(*args)
  super(*args)
  set_state(self.class.initial_state_class)
  self.class.delegate_all_state_events
end

#set_state(state_class) ⇒ Object



65
66
67
# File 'lib/state_pattern.rb', line 65

def set_state(state_class)
  self.current_state = state_class.new(self)
end

#stateObject



87
88
89
# File 'lib/state_pattern.rb', line 87

def state
  self.current_state.state
end

#transition_to(state_class) ⇒ Object



74
75
76
77
# File 'lib/state_pattern.rb', line 74

def transition_to(state_class)
  raise InvalidTransitionException.new(self.current_state.class, state_class, self.current_event) unless self.valid_transition?(self.current_state.class, state_class)
  set_state(state_class)
end

#valid_transition?(from_module, to_module) ⇒ Boolean

Returns:

  • (Boolean)


79
80
81
82
83
84
85
# File 'lib/state_pattern.rb', line 79

def valid_transition?(from_module, to_module)
  trans = self.class.transitions_hash
  return true if trans.nil?

  valid_transition_targets = trans[from_module] || trans[[from_module, current_event]]
  valid_transition_targets && valid_transition_targets.include?(to_module)
end