Module: Transitions

Includes:
Presenter
Defined in:
lib/transitions.rb,
lib/transitions/event.rb,
lib/transitions/state.rb,
lib/transitions/machine.rb,
lib/transitions/version.rb,
lib/transitions/presenter.rb,
lib/transitions/state_transition.rb

Defined Under Namespace

Modules: ClassMethods, Presenter Classes: Event, InvalidMethodOverride, InvalidTransition, Machine, State, StateTransition

Constant Summary collapse

VERSION =
'1.0.0'

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Presenter

#available_events, #available_states

Class Method Details

.active_model_descendant?(klazz) ⇒ Boolean

Returns:

  • (Boolean)


86
87
88
# File 'lib/transitions.rb', line 86

def self.active_model_descendant?(klazz)
  defined?(ActiveModel) && klazz.included_modules.include?(ActiveModel::Dirty) # Checking directly for "ActiveModel" wouldn't work so we use some arbitrary module close to it.
end

.included(base) ⇒ Object



42
43
44
# File 'lib/transitions.rb', line 42

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

Instance Method Details

#available_transitionsObject



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

def available_transitions
  self.class.get_state_machine.events_for(current_state)
end

#can_transition?(*events) ⇒ Boolean

Returns:

  • (Boolean)


62
63
64
65
66
# File 'lib/transitions.rb', line 62

def can_transition?(*events)
  events.all? do |event|
    self.class.get_state_machine.events_for(current_state).include?(event.to_sym)
  end
end

#cant_transition?(*events) ⇒ Boolean

Returns:

  • (Boolean)


68
69
70
# File 'lib/transitions.rb', line 68

def cant_transition?(*events)
  !can_transition?(*events)
end

#current_stateObject



72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/transitions.rb', line 72

def current_state
  sm   = self.class.get_state_machine
  ivar = sm.current_state_variable

  value = instance_variable_get(ivar)
  return value if value

  if Transitions.active_model_descendant?(self.class)
    value = instance_variable_set(ivar, read_state)
  end

  !(value.nil? || value.to_s.empty?) ? value : sm.initial_state
end

#update_current_state(new_state, persist = false) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
# File 'lib/transitions.rb', line 46

def update_current_state(new_state, persist = false)
  sm   = self.class.get_state_machine
  ivar = sm.current_state_variable

  if Transitions.active_model_descendant?(self.class)
    write_state(new_state) if persist
    write_state_without_persistence(new_state) # TODO This seems like a duplicate, `write_new` already calls `write_state_without_persistence`.
  end

  instance_variable_set(ivar, new_state)
end