hsume2-state_machine 1.0.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (110) hide show
  1. data/CHANGELOG.rdoc +413 -0
  2. data/LICENSE +20 -0
  3. data/README.rdoc +717 -0
  4. data/Rakefile +77 -0
  5. data/examples/AutoShop_state.png +0 -0
  6. data/examples/Car_state.png +0 -0
  7. data/examples/TrafficLight_state.png +0 -0
  8. data/examples/Vehicle_state.png +0 -0
  9. data/examples/auto_shop.rb +11 -0
  10. data/examples/car.rb +19 -0
  11. data/examples/merb-rest/controller.rb +51 -0
  12. data/examples/merb-rest/model.rb +28 -0
  13. data/examples/merb-rest/view_edit.html.erb +24 -0
  14. data/examples/merb-rest/view_index.html.erb +23 -0
  15. data/examples/merb-rest/view_new.html.erb +13 -0
  16. data/examples/merb-rest/view_show.html.erb +17 -0
  17. data/examples/rails-rest/controller.rb +43 -0
  18. data/examples/rails-rest/migration.rb +11 -0
  19. data/examples/rails-rest/model.rb +23 -0
  20. data/examples/rails-rest/view_edit.html.erb +25 -0
  21. data/examples/rails-rest/view_index.html.erb +23 -0
  22. data/examples/rails-rest/view_new.html.erb +14 -0
  23. data/examples/rails-rest/view_show.html.erb +17 -0
  24. data/examples/traffic_light.rb +7 -0
  25. data/examples/vehicle.rb +31 -0
  26. data/init.rb +1 -0
  27. data/lib/state_machine.rb +448 -0
  28. data/lib/state_machine/alternate_machine.rb +79 -0
  29. data/lib/state_machine/assertions.rb +36 -0
  30. data/lib/state_machine/branch.rb +224 -0
  31. data/lib/state_machine/callback.rb +236 -0
  32. data/lib/state_machine/condition_proxy.rb +94 -0
  33. data/lib/state_machine/error.rb +13 -0
  34. data/lib/state_machine/eval_helpers.rb +86 -0
  35. data/lib/state_machine/event.rb +304 -0
  36. data/lib/state_machine/event_collection.rb +139 -0
  37. data/lib/state_machine/extensions.rb +149 -0
  38. data/lib/state_machine/initializers.rb +4 -0
  39. data/lib/state_machine/initializers/merb.rb +1 -0
  40. data/lib/state_machine/initializers/rails.rb +25 -0
  41. data/lib/state_machine/integrations.rb +110 -0
  42. data/lib/state_machine/integrations/active_model.rb +502 -0
  43. data/lib/state_machine/integrations/active_model/locale.rb +11 -0
  44. data/lib/state_machine/integrations/active_model/observer.rb +45 -0
  45. data/lib/state_machine/integrations/active_model/versions.rb +31 -0
  46. data/lib/state_machine/integrations/active_record.rb +424 -0
  47. data/lib/state_machine/integrations/active_record/locale.rb +20 -0
  48. data/lib/state_machine/integrations/active_record/versions.rb +143 -0
  49. data/lib/state_machine/integrations/base.rb +91 -0
  50. data/lib/state_machine/integrations/data_mapper.rb +392 -0
  51. data/lib/state_machine/integrations/data_mapper/observer.rb +210 -0
  52. data/lib/state_machine/integrations/data_mapper/versions.rb +62 -0
  53. data/lib/state_machine/integrations/mongo_mapper.rb +272 -0
  54. data/lib/state_machine/integrations/mongo_mapper/locale.rb +4 -0
  55. data/lib/state_machine/integrations/mongo_mapper/versions.rb +110 -0
  56. data/lib/state_machine/integrations/mongoid.rb +357 -0
  57. data/lib/state_machine/integrations/mongoid/locale.rb +4 -0
  58. data/lib/state_machine/integrations/mongoid/versions.rb +18 -0
  59. data/lib/state_machine/integrations/sequel.rb +428 -0
  60. data/lib/state_machine/integrations/sequel/versions.rb +36 -0
  61. data/lib/state_machine/machine.rb +1873 -0
  62. data/lib/state_machine/machine_collection.rb +87 -0
  63. data/lib/state_machine/matcher.rb +123 -0
  64. data/lib/state_machine/matcher_helpers.rb +54 -0
  65. data/lib/state_machine/node_collection.rb +157 -0
  66. data/lib/state_machine/path.rb +120 -0
  67. data/lib/state_machine/path_collection.rb +90 -0
  68. data/lib/state_machine/state.rb +271 -0
  69. data/lib/state_machine/state_collection.rb +112 -0
  70. data/lib/state_machine/transition.rb +458 -0
  71. data/lib/state_machine/transition_collection.rb +244 -0
  72. data/lib/tasks/state_machine.rake +1 -0
  73. data/lib/tasks/state_machine.rb +27 -0
  74. data/test/files/en.yml +17 -0
  75. data/test/files/switch.rb +11 -0
  76. data/test/functional/alternate_state_machine_test.rb +122 -0
  77. data/test/functional/state_machine_test.rb +993 -0
  78. data/test/test_helper.rb +4 -0
  79. data/test/unit/assertions_test.rb +40 -0
  80. data/test/unit/branch_test.rb +890 -0
  81. data/test/unit/callback_test.rb +701 -0
  82. data/test/unit/condition_proxy_test.rb +328 -0
  83. data/test/unit/error_test.rb +43 -0
  84. data/test/unit/eval_helpers_test.rb +222 -0
  85. data/test/unit/event_collection_test.rb +358 -0
  86. data/test/unit/event_test.rb +985 -0
  87. data/test/unit/integrations/active_model_test.rb +1097 -0
  88. data/test/unit/integrations/active_record_test.rb +2021 -0
  89. data/test/unit/integrations/base_test.rb +99 -0
  90. data/test/unit/integrations/data_mapper_test.rb +1909 -0
  91. data/test/unit/integrations/mongo_mapper_test.rb +1611 -0
  92. data/test/unit/integrations/mongoid_test.rb +1591 -0
  93. data/test/unit/integrations/sequel_test.rb +1523 -0
  94. data/test/unit/integrations_test.rb +61 -0
  95. data/test/unit/invalid_event_test.rb +20 -0
  96. data/test/unit/invalid_parallel_transition_test.rb +18 -0
  97. data/test/unit/invalid_transition_test.rb +77 -0
  98. data/test/unit/machine_collection_test.rb +599 -0
  99. data/test/unit/machine_test.rb +3043 -0
  100. data/test/unit/matcher_helpers_test.rb +37 -0
  101. data/test/unit/matcher_test.rb +155 -0
  102. data/test/unit/node_collection_test.rb +217 -0
  103. data/test/unit/path_collection_test.rb +266 -0
  104. data/test/unit/path_test.rb +485 -0
  105. data/test/unit/state_collection_test.rb +310 -0
  106. data/test/unit/state_machine_test.rb +31 -0
  107. data/test/unit/state_test.rb +924 -0
  108. data/test/unit/transition_collection_test.rb +2102 -0
  109. data/test/unit/transition_test.rb +1541 -0
  110. metadata +207 -0
@@ -0,0 +1,79 @@
1
+ module StateMachine
2
+ # Provides an alternate syntax for defining state machines
3
+ #
4
+ # For example,
5
+ #
6
+ # class Vehicle
7
+ # state_machine :initial => :parked, :action => :save, :syntax => :alternate do
8
+ # state :parked do
9
+ # event :ignite, :to => :idling, :if => :have_keys?
10
+ # end
11
+ #
12
+ # state :idling do
13
+ # event :park, :to => :parked, :unless => :no_spots?
14
+ # end
15
+ # end
16
+ # end
17
+ #
18
+ # Instead of,
19
+ #
20
+ # class Vehicle
21
+ # state_machine :initial => :parked, :action => :save do
22
+ # event :ignite do
23
+ # transition :parked => :idling, :if => :have_keys?
24
+ # end
25
+ #
26
+ # event :park do
27
+ # transition :idling => :parked, :unless => :no_spots?
28
+ # end
29
+ # end
30
+ # end
31
+ #
32
+ # Also supports usage of :any, :all, and :same as valid states.
33
+ class AlternateMachine
34
+ include MatcherHelpers
35
+
36
+ class InvalidEventError < StandardError
37
+ end
38
+
39
+ def initialize(&block)
40
+ @queued_sends = []
41
+ instance_eval(&block) if block_given?
42
+ end
43
+
44
+ def state(*args, &block)
45
+ @from_state = args.first
46
+ instance_eval(&block) if block_given?
47
+ ensure
48
+ @from_state = nil
49
+ end
50
+
51
+ def event(event_name, options = {})
52
+ to_state = options.delete(:to)
53
+ raise InvalidEventError.new("event must be called within a state definition") unless @from_state
54
+ @queued_sends << [event_name, @from_state, to_state, options]
55
+ end
56
+
57
+ def to_state_machine
58
+ queued_sends = @queued_sends
59
+ lambda {
60
+ queued_sends.each do |args|
61
+ case args.length
62
+ when 2 # method_missing
63
+ args, block = args
64
+ send(*args, &block)
65
+ when 4 # event transition
66
+ event_name, from, to, options = args
67
+ event event_name do
68
+ transition options.merge(from => to)
69
+ end
70
+ end
71
+ end
72
+ }
73
+ end
74
+
75
+ def method_missing(*args, &block)
76
+ @queued_sends << [args, block]
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,36 @@
1
+ module StateMachine
2
+ # Provides a set of helper methods for making assertions about the content
3
+ # of various objects
4
+ module Assertions
5
+ # Validates that the given hash *only* includes the specified valid keys.
6
+ # If any invalid keys are found, an ArgumentError will be raised.
7
+ #
8
+ # == Examples
9
+ #
10
+ # options = {:name => 'John Smith', :age => 30}
11
+ #
12
+ # assert_valid_keys(options, :name) # => ArgumentError: Invalid key(s): age
13
+ # assert_valid_keys(options, 'name', 'age') # => ArgumentError: Invalid key(s): age, name
14
+ # assert_valid_keys(options, :name, :age) # => nil
15
+ def assert_valid_keys(hash, *valid_keys)
16
+ invalid_keys = hash.keys - valid_keys
17
+ raise ArgumentError, "Invalid key(s): #{invalid_keys.join(', ')}" unless invalid_keys.empty?
18
+ end
19
+
20
+ # Validates that the given hash only includes at *most* one of a set of
21
+ # exclusive keys. If more than one key is found, an ArgumentError will be
22
+ # raised.
23
+ #
24
+ # == Examples
25
+ #
26
+ # options = {:only => :on, :except => :off}
27
+ # assert_exclusive_keys(options, :only) # => nil
28
+ # assert_exclusive_keys(options, :except) # => nil
29
+ # assert_exclusive_keys(options, :only, :except) # => ArgumentError: Conflicting keys: only, except
30
+ # assert_exclusive_keys(options, :only, :except, :with) # => ArgumentError: Conflicting keys: only, except
31
+ def assert_exclusive_keys(hash, *exclusive_keys)
32
+ conflicting_keys = exclusive_keys & hash.keys
33
+ raise ArgumentError, "Conflicting keys: #{conflicting_keys.join(', ')}" unless conflicting_keys.length <= 1
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,224 @@
1
+ require 'state_machine/matcher'
2
+ require 'state_machine/eval_helpers'
3
+ require 'state_machine/assertions'
4
+
5
+ module StateMachine
6
+ # Represents a set of requirements that must be met in order for a transition
7
+ # or callback to occur. Branches verify that the event, from state, and to
8
+ # state of the transition match, in addition to if/unless conditionals for
9
+ # an object's state.
10
+ class Branch
11
+ include Assertions
12
+ include EvalHelpers
13
+
14
+ # The condition that must be met on an object
15
+ attr_reader :if_condition
16
+
17
+ # The condition that must *not* be met on an object
18
+ attr_reader :unless_condition
19
+
20
+ # The requirement for verifying the event being matched
21
+ attr_reader :event_requirement
22
+
23
+ # One or more requirements for verifying the states being matched. All
24
+ # requirements contain a mapping of {:from => matcher, :to => matcher}.
25
+ attr_reader :state_requirements
26
+
27
+ # A list of all of the states known to this branch. This will pull states
28
+ # from the following options (in the same order):
29
+ # * +from+ / +except_from+
30
+ # * +to+ / +except_to+
31
+ attr_reader :known_states
32
+
33
+ # Creates a new branch
34
+ def initialize(options = {}) #:nodoc:
35
+ # Build conditionals
36
+ @if_condition = options.delete(:if)
37
+ @unless_condition = options.delete(:unless)
38
+
39
+ # Build event requirement
40
+ @event_requirement = build_matcher(options, :on, :except_on)
41
+
42
+ if (options.keys - [:from, :to, :on, :except_from, :except_to, :except_on]).empty?
43
+ # Explicit from/to requirements specified
44
+ @state_requirements = [{:from => build_matcher(options, :from, :except_from), :to => build_matcher(options, :to, :except_to)}]
45
+ else
46
+ # Separate out the event requirement
47
+ options.delete(:on)
48
+ options.delete(:except_on)
49
+
50
+ # Implicit from/to requirements specified
51
+ @state_requirements = options.collect do |from, to|
52
+ from = WhitelistMatcher.new(from) unless from.is_a?(Matcher)
53
+ to = WhitelistMatcher.new(to) unless to.is_a?(Matcher)
54
+ {:from => from, :to => to}
55
+ end
56
+ end
57
+
58
+ # Track known states. The order that requirements are iterated is based
59
+ # on the priority in which tracked states should be added.
60
+ @known_states = []
61
+ @state_requirements.each do |state_requirement|
62
+ [:from, :to].each {|option| @known_states |= state_requirement[option].values}
63
+ end
64
+ end
65
+
66
+ # Determines whether the given object / query matches the requirements
67
+ # configured for this branch. In addition to matching the event, from state,
68
+ # and to state, this will also check whether the configured :if/:unless
69
+ # conditions pass on the given object.
70
+ #
71
+ # == Examples
72
+ #
73
+ # branch = StateMachine::Branch.new(:parked => :idling, :on => :ignite)
74
+ #
75
+ # # Successful
76
+ # branch.matches?(object, :on => :ignite) # => true
77
+ # branch.matches?(object, :from => nil) # => true
78
+ # branch.matches?(object, :from => :parked) # => true
79
+ # branch.matches?(object, :to => :idling) # => true
80
+ # branch.matches?(object, :from => :parked, :to => :idling) # => true
81
+ # branch.matches?(object, :on => :ignite, :from => :parked, :to => :idling) # => true
82
+ #
83
+ # # Unsuccessful
84
+ # branch.matches?(object, :on => :park) # => false
85
+ # branch.matches?(object, :from => :idling) # => false
86
+ # branch.matches?(object, :to => :first_gear) # => false
87
+ # branch.matches?(object, :from => :parked, :to => :first_gear) # => false
88
+ # branch.matches?(object, :on => :park, :from => :parked, :to => :idling) # => false
89
+ def matches?(object, query = {})
90
+ !match(object, query).nil?
91
+ end
92
+
93
+ # Attempts to match the given object / query against the set of requirements
94
+ # configured for this branch. In addition to matching the event, from state,
95
+ # and to state, this will also check whether the configured :if/:unless
96
+ # conditions pass on the given object.
97
+ #
98
+ # If a match is found, then the event/state requirements that the query
99
+ # passed successfully will be returned. Otherwise, nil is returned if there
100
+ # was no match.
101
+ #
102
+ # Query options:
103
+ # * <tt>:from</tt> - One or more states being transitioned from. If none
104
+ # are specified, then this will always match.
105
+ # * <tt>:to</tt> - One or more states being transitioned to. If none are
106
+ # specified, then this will always match.
107
+ # * <tt>:on</tt> - One or more events that fired the transition. If none
108
+ # are specified, then this will always match.
109
+ # * <tt>:guard</tt> - Whether to guard matches with the if/unless
110
+ # conditionals defined for this branch. Default is true.
111
+ #
112
+ # == Examples
113
+ #
114
+ # branch = StateMachine::Branch.new(:parked => :idling, :on => :ignite)
115
+ #
116
+ # branch.match(object, :on => :ignite) # => {:to => ..., :from => ..., :on => ...}
117
+ # branch.match(object, :on => :park) # => nil
118
+ def match(object, query = {})
119
+ assert_valid_keys(query, :from, :to, :on, :guard)
120
+
121
+ if (match = match_query(query)) && matches_conditions?(object, query)
122
+ match
123
+ end
124
+ end
125
+
126
+ # Draws a representation of this branch on the given graph. This will draw
127
+ # an edge between every state this branch matches *from* to either the
128
+ # configured to state or, if none specified, then a loopback to the from
129
+ # state.
130
+ #
131
+ # For example, if the following from states are configured:
132
+ # * +idling+
133
+ # * +first_gear+
134
+ # * +backing_up+
135
+ #
136
+ # ...and the to state is +parked+, then the following edges will be created:
137
+ # * +idling+ -> +parked+
138
+ # * +first_gear+ -> +parked+
139
+ # * +backing_up+ -> +parked+
140
+ #
141
+ # Each edge will be labeled with the name of the event that would cause the
142
+ # transition.
143
+ #
144
+ # The collection of edges generated on the graph will be returned.
145
+ def draw(graph, event, valid_states)
146
+ state_requirements.inject([]) do |edges, state_requirement|
147
+ # From states determined based on the known valid states
148
+ from_states = state_requirement[:from].filter(valid_states)
149
+
150
+ # If a to state is not specified, then it's a loopback and each from
151
+ # state maps back to itself
152
+ if state_requirement[:to].values.empty?
153
+ loopback = true
154
+ else
155
+ to_state = state_requirement[:to].values.first
156
+ to_state = to_state ? to_state.to_s : 'nil'
157
+ loopback = false
158
+ end
159
+
160
+ # Generate an edge between each from and to state
161
+ from_states.each do |from_state|
162
+ from_state = from_state ? from_state.to_s : 'nil'
163
+ edges << graph.add_edge(from_state, loopback ? from_state : to_state, :label => event.to_s)
164
+ end
165
+
166
+ edges
167
+ end
168
+ end
169
+
170
+ protected
171
+ # Builds a matcher strategy to use for the given options. If neither a
172
+ # whitelist nor a blacklist option is specified, then an AllMatcher is
173
+ # built.
174
+ def build_matcher(options, whitelist_option, blacklist_option)
175
+ assert_exclusive_keys(options, whitelist_option, blacklist_option)
176
+
177
+ if options.include?(whitelist_option)
178
+ WhitelistMatcher.new(options[whitelist_option])
179
+ elsif options.include?(blacklist_option)
180
+ BlacklistMatcher.new(options[blacklist_option])
181
+ else
182
+ AllMatcher.instance
183
+ end
184
+ end
185
+
186
+ # Verifies that all configured requirements (event and state) match the
187
+ # given query. If a match is found, then a hash containing the
188
+ # event/state requirements that passed will be returned; otherwise, nil.
189
+ def match_query(query)
190
+ query ||= {}
191
+
192
+ if match_event(query) && (state_requirement = match_states(query))
193
+ state_requirement.merge(:on => event_requirement)
194
+ end
195
+ end
196
+
197
+ # Verifies that the event requirement matches the given query
198
+ def match_event(query)
199
+ matches_requirement?(query, :on, event_requirement)
200
+ end
201
+
202
+ # Verifies that the state requirements match the given query. If a
203
+ # matching requirement is found, then it is returned.
204
+ def match_states(query)
205
+ state_requirements.detect do |state_requirement|
206
+ [:from, :to].all? {|option| matches_requirement?(query, option, state_requirement[option])}
207
+ end
208
+ end
209
+
210
+ # Verifies that an option in the given query matches the values required
211
+ # for that option
212
+ def matches_requirement?(query, option, requirement)
213
+ !query.include?(option) || requirement.matches?(query[option], query)
214
+ end
215
+
216
+ # Verifies that the conditionals for this branch evaluate to true for the
217
+ # given object
218
+ def matches_conditions?(object, query)
219
+ query[:guard] == false ||
220
+ Array(if_condition).all? {|condition| evaluate_method(object, condition)} &&
221
+ !Array(unless_condition).any? {|condition| evaluate_method(object, condition)}
222
+ end
223
+ end
224
+ end
@@ -0,0 +1,236 @@
1
+ require 'state_machine/branch'
2
+ require 'state_machine/eval_helpers'
3
+
4
+ module StateMachine
5
+ # Callbacks represent hooks into objects that allow logic to be triggered
6
+ # before, after, or around a specific set of transitions.
7
+ class Callback
8
+ include EvalHelpers
9
+
10
+ class << self
11
+ # Determines whether to automatically bind the callback to the object
12
+ # being transitioned. This only applies to callbacks that are defined as
13
+ # lambda blocks (or Procs). Some integrations, such as DataMapper, handle
14
+ # callbacks by executing them bound to the object involved, while other
15
+ # integrations, such as ActiveRecord, pass the object as an argument to
16
+ # the callback. This can be configured on an application-wide basis by
17
+ # setting this configuration to +true+ or +false+. The default value
18
+ # is +false+.
19
+ #
20
+ # *Note* that the DataMapper and Sequel integrations automatically
21
+ # configure this value on a per-callback basis, so it does not have to
22
+ # be enabled application-wide.
23
+ #
24
+ # == Examples
25
+ #
26
+ # When not bound to the object:
27
+ #
28
+ # class Vehicle
29
+ # state_machine do
30
+ # before_transition do |vehicle|
31
+ # vehicle.set_alarm
32
+ # end
33
+ # end
34
+ #
35
+ # def set_alarm
36
+ # ...
37
+ # end
38
+ # end
39
+ #
40
+ # When bound to the object:
41
+ #
42
+ # StateMachine::Callback.bind_to_object = true
43
+ #
44
+ # class Vehicle
45
+ # state_machine do
46
+ # before_transition do
47
+ # self.set_alarm
48
+ # end
49
+ # end
50
+ #
51
+ # def set_alarm
52
+ # ...
53
+ # end
54
+ # end
55
+ attr_accessor :bind_to_object
56
+
57
+ # The application-wide terminator to use for callbacks when not
58
+ # explicitly defined. Terminators determine whether to cancel a
59
+ # callback chain based on the return value of the callback.
60
+ #
61
+ # See StateMachine::Callback#terminator for more information.
62
+ attr_accessor :terminator
63
+ end
64
+
65
+ # The type of callback chain this callback is for. This can be one of the
66
+ # following:
67
+ # * +before+
68
+ # * +after+
69
+ # * +around+
70
+ # * +failure+
71
+ attr_accessor :type
72
+
73
+ # An optional block for determining whether to cancel the callback chain
74
+ # based on the return value of the callback. By default, the callback
75
+ # chain never cancels based on the return value (i.e. there is no implicit
76
+ # terminator). Certain integrations, such as ActiveRecord and Sequel,
77
+ # change this default value.
78
+ #
79
+ # == Examples
80
+ #
81
+ # Canceling the callback chain without a terminator:
82
+ #
83
+ # class Vehicle
84
+ # state_machine do
85
+ # before_transition do |vehicle|
86
+ # throw :halt
87
+ # end
88
+ # end
89
+ # end
90
+ #
91
+ # Canceling the callback chain with a terminator value of +false+:
92
+ #
93
+ # class Vehicle
94
+ # state_machine do
95
+ # before_transition do |vehicle|
96
+ # false
97
+ # end
98
+ # end
99
+ # end
100
+ attr_reader :terminator
101
+
102
+ # The branch that determines whether or not this callback can be invoked
103
+ # based on the context of the transition. The event, from state, and
104
+ # to state must all match in order for the branch to pass.
105
+ #
106
+ # See StateMachine::Branch for more information.
107
+ attr_reader :branch
108
+
109
+ # Creates a new callback that can get called based on the configured
110
+ # options.
111
+ #
112
+ # In addition to the possible configuration options for branches, the
113
+ # following options can be configured:
114
+ # * <tt>:bind_to_object</tt> - Whether to bind the callback to the object involved.
115
+ # If set to false, the object will be passed as a parameter instead.
116
+ # Default is integration-specific or set to the application default.
117
+ # * <tt>:terminator</tt> - A block/proc that determines what callback
118
+ # results should cause the callback chain to halt (if not using the
119
+ # default <tt>throw :halt</tt> technique).
120
+ #
121
+ # More information about how those options affect the behavior of the
122
+ # callback can be found in their attribute definitions.
123
+ def initialize(type, *args, &block)
124
+ @type = type
125
+ raise ArgumentError, 'Type must be :before, :after, :around, or :failure' unless [:before, :after, :around, :failure].include?(type)
126
+
127
+ options = args.last.is_a?(Hash) ? args.pop : {}
128
+ @methods = args
129
+ @methods.concat(Array(options.delete(:do)))
130
+ @methods << block if block_given?
131
+ raise ArgumentError, 'Method(s) for callback must be specified' unless @methods.any?
132
+
133
+ options = {:bind_to_object => self.class.bind_to_object, :terminator => self.class.terminator}.merge(options)
134
+
135
+ # Proxy lambda blocks so that they're bound to the object
136
+ bind_to_object = options.delete(:bind_to_object)
137
+ @methods.map! do |method|
138
+ bind_to_object && method.is_a?(Proc) ? bound_method(method) : method
139
+ end
140
+
141
+ @terminator = options.delete(:terminator)
142
+ @branch = Branch.new(options)
143
+ end
144
+
145
+ # Gets a list of the states known to this callback by looking at the
146
+ # branch's known states
147
+ def known_states
148
+ branch.known_states
149
+ end
150
+
151
+ # Runs the callback as long as the transition context matches the branch
152
+ # requirements configured for this callback. If a block is provided, it
153
+ # will be called when the last method has run.
154
+ #
155
+ # If a terminator has been configured and it matches the result from the
156
+ # evaluated method, then the callback chain should be halted.
157
+ def call(object, context = {}, *args, &block)
158
+ if @branch.matches?(object, context)
159
+ run_methods(object, context, 0, *args, &block)
160
+ true
161
+ else
162
+ false
163
+ end
164
+ end
165
+
166
+ private
167
+ # Runs all of the methods configured for this callback.
168
+ #
169
+ # When running +around+ callbacks, this will evaluate each method and
170
+ # yield when the last method has yielded. The callback will only halt if
171
+ # one of the methods does not yield.
172
+ #
173
+ # For all other types of callbacks, this will evaluate each method in
174
+ # order. The callback will only halt if the resulting value from the
175
+ # method passes the terminator.
176
+ def run_methods(object, context = {}, index = 0, *args, &block)
177
+ if type == :around
178
+ if method = @methods[index]
179
+ yielded = false
180
+ evaluate_method(object, method, *args) do
181
+ yielded = true
182
+ run_methods(object, context, index + 1, *args, &block)
183
+ end
184
+
185
+ throw :halt unless yielded
186
+ else
187
+ yield if block_given?
188
+ end
189
+ else
190
+ @methods.each do |method|
191
+ result = evaluate_method(object, method, *args)
192
+ throw :halt if @terminator && @terminator.call(result)
193
+ end
194
+ end
195
+ end
196
+
197
+ # Generates a method that can be bound to the object being transitioned
198
+ # when the callback is invoked
199
+ def bound_method(block)
200
+ type = self.type
201
+ arity = block.arity
202
+ arity += 1 if arity >= 0 # Make sure the object gets passed
203
+ arity += 1 if arity == 1 && type == :around # Make sure the block gets passed
204
+
205
+ method = if RUBY_VERSION >= '1.9'
206
+ lambda do |object, *args|
207
+ object.instance_exec(*args, &block)
208
+ end
209
+ else
210
+ # Generate a thread-safe unbound method that can be used on any object.
211
+ # This is a workaround for not having Ruby 1.9's instance_exec
212
+ unbound_method = Object.class_eval do
213
+ time = Time.now
214
+ method_name = "__bind_#{time.to_i}_#{time.usec}"
215
+ define_method(method_name, &block)
216
+ method = instance_method(method_name)
217
+ remove_method(method_name)
218
+ method
219
+ end
220
+
221
+ # Proxy calls to the method so that the method can be bound *and*
222
+ # the arguments are adjusted
223
+ lambda do |object, *args|
224
+ unbound_method.bind(object).call(*args)
225
+ end
226
+ end
227
+
228
+ # Proxy arity to the original block
229
+ (class << method; self; end).class_eval do
230
+ define_method(:arity) { arity }
231
+ end
232
+
233
+ method
234
+ end
235
+ end
236
+ end