-
Notifications
You must be signed in to change notification settings - Fork 7
/
event.rb
55 lines (48 loc) · 1.59 KB
/
event.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
require File.join(File.dirname(__FILE__), 'state_transition')
module AASM
module SupportingClasses
class Event
attr_reader :name, :success
def initialize(name, options = {}, &block)
@name = name
@success = options[:success]
@transitions = []
instance_eval(&block) if block
end
def fire(obj, to_state=nil, *args)
transitions = @transitions.select { |t| t.from == obj.aasm_current_state }
raise AASM::InvalidTransition, "Event '#{name}' cannot transition from '#{obj.aasm_current_state}'" if transitions.size == 0
next_state = nil
transitions.each do |transition|
next if to_state and !Array(transition.to).include?(to_state)
if transition.perform(obj)
next_state = to_state || Array(transition.to).first
transition.execute(obj, *args)
break
end
end
next_state
end
def transitions_from_state?(state)
@transitions.any? { |t| t.from == state }
end
def execute_success_callback(obj, success = nil)
callback = success || @success
case(callback)
when String, Symbol
obj.send(callback)
when Proc
callback.call(obj)
when Array
callback.each{|meth|self.execute_success_callback(obj, meth)}
end
end
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