2008-06-28 03:55:02 -04:00
|
|
|
module ActiveModel
|
|
|
|
module StateMachine
|
2009-05-29 22:45:13 -04:00
|
|
|
autoload :Event, 'active_model/state_machine/event'
|
|
|
|
autoload :Machine, 'active_model/state_machine/machine'
|
|
|
|
autoload :State, 'active_model/state_machine/state'
|
|
|
|
autoload :StateTransition, 'active_model/state_machine/state_transition'
|
|
|
|
|
2009-08-04 12:03:57 -04:00
|
|
|
extend ActiveSupport::Concern
|
2008-06-28 12:19:44 -04:00
|
|
|
|
2009-08-04 12:03:57 -04:00
|
|
|
class InvalidTransition < Exception
|
2008-06-28 03:55:02 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
module ClassMethods
|
|
|
|
def inherited(klass)
|
|
|
|
super
|
|
|
|
klass.state_machines = state_machines
|
|
|
|
end
|
|
|
|
|
|
|
|
def state_machines
|
|
|
|
@state_machines ||= {}
|
|
|
|
end
|
|
|
|
|
|
|
|
def state_machines=(value)
|
|
|
|
@state_machines = value ? value.dup : nil
|
|
|
|
end
|
|
|
|
|
|
|
|
def state_machine(name = nil, options = {}, &block)
|
|
|
|
if name.is_a?(Hash)
|
|
|
|
options = name
|
|
|
|
name = nil
|
|
|
|
end
|
|
|
|
name ||= :default
|
|
|
|
state_machines[name] ||= Machine.new(self, name)
|
|
|
|
block ? state_machines[name].update(options, &block) : state_machines[name]
|
|
|
|
end
|
2008-11-22 21:37:08 -05:00
|
|
|
|
|
|
|
def define_state_query_method(state_name)
|
|
|
|
name = "#{state_name}?"
|
|
|
|
undef_method(name) if method_defined?(name)
|
|
|
|
class_eval "def #{name}; current_state.to_s == %(#{state_name}) end"
|
|
|
|
end
|
2008-06-28 03:55:02 -04:00
|
|
|
end
|
|
|
|
|
2008-06-28 14:33:50 -04:00
|
|
|
def current_state(name = nil, new_state = nil, persist = false)
|
2008-06-28 03:55:02 -04:00
|
|
|
sm = self.class.state_machine(name)
|
2008-06-28 14:33:50 -04:00
|
|
|
ivar = sm.current_state_variable
|
2008-06-28 12:19:44 -04:00
|
|
|
if name && new_state
|
2008-06-28 14:33:50 -04:00
|
|
|
if persist && respond_to?(:write_state)
|
|
|
|
write_state(sm, new_state)
|
|
|
|
end
|
|
|
|
|
|
|
|
if respond_to?(:write_state_without_persistence)
|
|
|
|
write_state_without_persistence(sm, new_state)
|
|
|
|
end
|
|
|
|
|
2008-06-28 12:19:44 -04:00
|
|
|
instance_variable_set(ivar, new_state)
|
|
|
|
else
|
2008-06-28 14:33:50 -04:00
|
|
|
instance_variable_set(ivar, nil) unless instance_variable_defined?(ivar)
|
|
|
|
value = instance_variable_get(ivar)
|
|
|
|
return value if value
|
|
|
|
|
|
|
|
if respond_to?(:read_state)
|
|
|
|
value = instance_variable_set(ivar, read_state(sm))
|
|
|
|
end
|
|
|
|
|
|
|
|
value || sm.initial_state
|
2008-06-28 12:19:44 -04:00
|
|
|
end
|
2008-06-28 03:55:02 -04:00
|
|
|
end
|
|
|
|
end
|
2008-11-16 00:05:03 -05:00
|
|
|
end
|