2008-01-07 14:11:38 -05:00
|
|
|
require File.join(File.dirname(__FILE__), 'state_transition')
|
|
|
|
|
|
|
|
module AASM
|
|
|
|
module SupportingClasses
|
|
|
|
class Event
|
2008-05-20 15:27:35 -04:00
|
|
|
attr_reader :name, :success
|
2009-04-09 02:25:16 -03:00
|
|
|
|
2008-05-20 15:27:35 -04:00
|
|
|
def initialize(name, options = {}, &block)
|
2008-01-07 15:07:38 -05:00
|
|
|
@name = name
|
2008-05-20 15:27:35 -04:00
|
|
|
@success = options[:success]
|
2008-01-07 14:11:38 -05:00
|
|
|
@transitions = []
|
|
|
|
instance_eval(&block) if block
|
|
|
|
end
|
|
|
|
|
2008-06-03 23:44:25 -05:00
|
|
|
def fire(obj, to_state=nil, *args)
|
2008-01-08 09:39:00 -05:00
|
|
|
transitions = @transitions.select { |t| t.from == obj.aasm_current_state }
|
2008-07-09 16:17:35 -07:00
|
|
|
raise AASM::InvalidTransition, "Event '#{name}' cannot transition from '#{obj.aasm_current_state}'" if transitions.size == 0
|
2008-02-21 10:46:06 -05:00
|
|
|
|
|
|
|
next_state = nil
|
|
|
|
transitions.each do |transition|
|
2008-06-03 23:44:25 -05:00
|
|
|
next if to_state and !Array(transition.to).include?(to_state)
|
2008-02-21 10:46:06 -05:00
|
|
|
if transition.perform(obj)
|
2008-06-03 23:44:25 -05:00
|
|
|
next_state = to_state || Array(transition.to).first
|
|
|
|
transition.execute(obj, *args)
|
2008-02-21 10:46:06 -05:00
|
|
|
break
|
|
|
|
end
|
2008-01-07 14:11:38 -05:00
|
|
|
end
|
2008-02-21 10:46:06 -05:00
|
|
|
next_state
|
2008-01-07 14:11:38 -05:00
|
|
|
end
|
|
|
|
|
2008-02-28 08:33:40 -05:00
|
|
|
def transitions_from_state?(state)
|
|
|
|
@transitions.any? { |t| t.from == state }
|
|
|
|
end
|
2009-04-09 02:14:02 -03:00
|
|
|
|
|
|
|
def execute_success_callback(obj, success = nil)
|
|
|
|
callback = success || @success
|
|
|
|
case(callback)
|
2009-02-06 22:49:24 +08:00
|
|
|
when String, Symbol
|
2009-04-09 02:14:02 -03:00
|
|
|
obj.send(callback)
|
2009-02-06 22:49:24 +08:00
|
|
|
when Proc
|
2009-04-09 02:14:02 -03:00
|
|
|
callback.call(obj)
|
|
|
|
when Array
|
|
|
|
callback.each{|meth|self.execute_success_callback(obj, meth)}
|
2008-10-09 10:53:39 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2008-01-07 14:11:38 -05:00
|
|
|
private
|
|
|
|
def transitions(trans_opts)
|
|
|
|
Array(trans_opts[:from]).each do |s|
|
|
|
|
@transitions << SupportingClasses::StateTransition.new(trans_opts.merge({:from => s.to_sym}))
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|