spree-state_machine 2.0.0.beta1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (140) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +8 -0
  3. data/.travis.yml +12 -0
  4. data/.yardopts +5 -0
  5. data/CHANGELOG.md +502 -0
  6. data/Gemfile +3 -0
  7. data/LICENSE +20 -0
  8. data/README.md +1246 -0
  9. data/Rakefile +20 -0
  10. data/examples/AutoShop_state.png +0 -0
  11. data/examples/Car_state.png +0 -0
  12. data/examples/Gemfile +5 -0
  13. data/examples/Gemfile.lock +14 -0
  14. data/examples/TrafficLight_state.png +0 -0
  15. data/examples/Vehicle_state.png +0 -0
  16. data/examples/auto_shop.rb +13 -0
  17. data/examples/car.rb +21 -0
  18. data/examples/doc/AutoShop.html +2856 -0
  19. data/examples/doc/AutoShop_state.png +0 -0
  20. data/examples/doc/Car.html +919 -0
  21. data/examples/doc/Car_state.png +0 -0
  22. data/examples/doc/TrafficLight.html +2230 -0
  23. data/examples/doc/TrafficLight_state.png +0 -0
  24. data/examples/doc/Vehicle.html +7921 -0
  25. data/examples/doc/Vehicle_state.png +0 -0
  26. data/examples/doc/_index.html +136 -0
  27. data/examples/doc/class_list.html +47 -0
  28. data/examples/doc/css/common.css +1 -0
  29. data/examples/doc/css/full_list.css +55 -0
  30. data/examples/doc/css/style.css +322 -0
  31. data/examples/doc/file_list.html +46 -0
  32. data/examples/doc/frames.html +13 -0
  33. data/examples/doc/index.html +136 -0
  34. data/examples/doc/js/app.js +205 -0
  35. data/examples/doc/js/full_list.js +173 -0
  36. data/examples/doc/js/jquery.js +16 -0
  37. data/examples/doc/method_list.html +734 -0
  38. data/examples/doc/top-level-namespace.html +105 -0
  39. data/examples/merb-rest/controller.rb +51 -0
  40. data/examples/merb-rest/model.rb +28 -0
  41. data/examples/merb-rest/view_edit.html.erb +24 -0
  42. data/examples/merb-rest/view_index.html.erb +23 -0
  43. data/examples/merb-rest/view_new.html.erb +13 -0
  44. data/examples/merb-rest/view_show.html.erb +17 -0
  45. data/examples/rails-rest/controller.rb +43 -0
  46. data/examples/rails-rest/migration.rb +7 -0
  47. data/examples/rails-rest/model.rb +23 -0
  48. data/examples/rails-rest/view__form.html.erb +34 -0
  49. data/examples/rails-rest/view_edit.html.erb +6 -0
  50. data/examples/rails-rest/view_index.html.erb +25 -0
  51. data/examples/rails-rest/view_new.html.erb +5 -0
  52. data/examples/rails-rest/view_show.html.erb +19 -0
  53. data/examples/traffic_light.rb +9 -0
  54. data/examples/vehicle.rb +33 -0
  55. data/lib/state_machine/assertions.rb +36 -0
  56. data/lib/state_machine/branch.rb +225 -0
  57. data/lib/state_machine/callback.rb +236 -0
  58. data/lib/state_machine/core.rb +7 -0
  59. data/lib/state_machine/core_ext/class/state_machine.rb +5 -0
  60. data/lib/state_machine/core_ext.rb +2 -0
  61. data/lib/state_machine/error.rb +13 -0
  62. data/lib/state_machine/eval_helpers.rb +87 -0
  63. data/lib/state_machine/event.rb +257 -0
  64. data/lib/state_machine/event_collection.rb +141 -0
  65. data/lib/state_machine/extensions.rb +149 -0
  66. data/lib/state_machine/graph.rb +92 -0
  67. data/lib/state_machine/helper_module.rb +17 -0
  68. data/lib/state_machine/initializers/rails.rb +25 -0
  69. data/lib/state_machine/initializers.rb +4 -0
  70. data/lib/state_machine/integrations/active_model/locale.rb +11 -0
  71. data/lib/state_machine/integrations/active_model/observer.rb +33 -0
  72. data/lib/state_machine/integrations/active_model/observer_update.rb +42 -0
  73. data/lib/state_machine/integrations/active_model/versions.rb +31 -0
  74. data/lib/state_machine/integrations/active_model.rb +585 -0
  75. data/lib/state_machine/integrations/active_record/locale.rb +20 -0
  76. data/lib/state_machine/integrations/active_record/versions.rb +123 -0
  77. data/lib/state_machine/integrations/active_record.rb +525 -0
  78. data/lib/state_machine/integrations/base.rb +100 -0
  79. data/lib/state_machine/integrations.rb +121 -0
  80. data/lib/state_machine/machine.rb +2287 -0
  81. data/lib/state_machine/machine_collection.rb +74 -0
  82. data/lib/state_machine/macro_methods.rb +522 -0
  83. data/lib/state_machine/matcher.rb +123 -0
  84. data/lib/state_machine/matcher_helpers.rb +54 -0
  85. data/lib/state_machine/node_collection.rb +222 -0
  86. data/lib/state_machine/path.rb +120 -0
  87. data/lib/state_machine/path_collection.rb +90 -0
  88. data/lib/state_machine/state.rb +297 -0
  89. data/lib/state_machine/state_collection.rb +112 -0
  90. data/lib/state_machine/state_context.rb +138 -0
  91. data/lib/state_machine/transition.rb +470 -0
  92. data/lib/state_machine/transition_collection.rb +245 -0
  93. data/lib/state_machine/version.rb +3 -0
  94. data/lib/state_machine/yard/handlers/base.rb +32 -0
  95. data/lib/state_machine/yard/handlers/event.rb +25 -0
  96. data/lib/state_machine/yard/handlers/machine.rb +344 -0
  97. data/lib/state_machine/yard/handlers/state.rb +25 -0
  98. data/lib/state_machine/yard/handlers/transition.rb +47 -0
  99. data/lib/state_machine/yard/handlers.rb +12 -0
  100. data/lib/state_machine/yard/templates/default/class/html/setup.rb +30 -0
  101. data/lib/state_machine/yard/templates/default/class/html/state_machines.erb +12 -0
  102. data/lib/state_machine/yard/templates.rb +3 -0
  103. data/lib/state_machine/yard.rb +8 -0
  104. data/lib/state_machine.rb +8 -0
  105. data/lib/yard-state_machine.rb +2 -0
  106. data/state_machine.gemspec +22 -0
  107. data/test/files/en.yml +17 -0
  108. data/test/files/switch.rb +15 -0
  109. data/test/functional/state_machine_test.rb +1066 -0
  110. data/test/test_helper.rb +7 -0
  111. data/test/unit/assertions_test.rb +40 -0
  112. data/test/unit/branch_test.rb +969 -0
  113. data/test/unit/callback_test.rb +704 -0
  114. data/test/unit/error_test.rb +43 -0
  115. data/test/unit/eval_helpers_test.rb +270 -0
  116. data/test/unit/event_collection_test.rb +398 -0
  117. data/test/unit/event_test.rb +1196 -0
  118. data/test/unit/graph_test.rb +98 -0
  119. data/test/unit/helper_module_test.rb +17 -0
  120. data/test/unit/integrations/active_model_test.rb +1245 -0
  121. data/test/unit/integrations/active_record_test.rb +2551 -0
  122. data/test/unit/integrations/base_test.rb +104 -0
  123. data/test/unit/integrations_test.rb +71 -0
  124. data/test/unit/invalid_event_test.rb +20 -0
  125. data/test/unit/invalid_parallel_transition_test.rb +18 -0
  126. data/test/unit/invalid_transition_test.rb +115 -0
  127. data/test/unit/machine_collection_test.rb +603 -0
  128. data/test/unit/machine_test.rb +3395 -0
  129. data/test/unit/matcher_helpers_test.rb +37 -0
  130. data/test/unit/matcher_test.rb +155 -0
  131. data/test/unit/node_collection_test.rb +362 -0
  132. data/test/unit/path_collection_test.rb +266 -0
  133. data/test/unit/path_test.rb +485 -0
  134. data/test/unit/state_collection_test.rb +352 -0
  135. data/test/unit/state_context_test.rb +441 -0
  136. data/test/unit/state_machine_test.rb +31 -0
  137. data/test/unit/state_test.rb +1101 -0
  138. data/test/unit/transition_collection_test.rb +2168 -0
  139. data/test/unit/transition_test.rb +1558 -0
  140. metadata +264 -0
@@ -0,0 +1,2287 @@
1
+ require 'state_machine/extensions'
2
+ require 'state_machine/assertions'
3
+ require 'state_machine/integrations'
4
+
5
+ require 'state_machine/helper_module'
6
+ require 'state_machine/state'
7
+ require 'state_machine/event'
8
+ require 'state_machine/callback'
9
+ require 'state_machine/node_collection'
10
+ require 'state_machine/state_collection'
11
+ require 'state_machine/event_collection'
12
+ require 'state_machine/path_collection'
13
+ require 'state_machine/matcher_helpers'
14
+
15
+ module StateMachine
16
+ # Represents a state machine for a particular attribute. State machines
17
+ # consist of states, events and a set of transitions that define how the
18
+ # state changes after a particular event is fired.
19
+ #
20
+ # A state machine will not know all of the possible states for an object
21
+ # unless they are referenced *somewhere* in the state machine definition.
22
+ # As a result, any unused states should be defined with the +other_states+
23
+ # or +state+ helper.
24
+ #
25
+ # == Actions
26
+ #
27
+ # When an action is configured for a state machine, it is invoked when an
28
+ # object transitions via an event. The success of the event becomes
29
+ # dependent on the success of the action. If the action is successful, then
30
+ # the transitioned state remains persisted. However, if the action fails
31
+ # (by returning false), the transitioned state will be rolled back.
32
+ #
33
+ # For example,
34
+ #
35
+ # class Vehicle
36
+ # attr_accessor :fail, :saving_state
37
+ #
38
+ # state_machine :initial => :parked, :action => :save do
39
+ # event :ignite do
40
+ # transition :parked => :idling
41
+ # end
42
+ #
43
+ # event :park do
44
+ # transition :idling => :parked
45
+ # end
46
+ # end
47
+ #
48
+ # def save
49
+ # @saving_state = state
50
+ # fail != true
51
+ # end
52
+ # end
53
+ #
54
+ # vehicle = Vehicle.new # => #<Vehicle:0xb7c27024 @state="parked">
55
+ # vehicle.save # => true
56
+ # vehicle.saving_state # => "parked" # The state was "parked" was save was called
57
+ #
58
+ # # Successful event
59
+ # vehicle.ignite # => true
60
+ # vehicle.saving_state # => "idling" # The state was "idling" when save was called
61
+ # vehicle.state # => "idling"
62
+ #
63
+ # # Failed event
64
+ # vehicle.fail = true
65
+ # vehicle.park # => false
66
+ # vehicle.saving_state # => "parked"
67
+ # vehicle.state # => "idling"
68
+ #
69
+ # As shown, even though the state is set prior to calling the +save+ action
70
+ # on the object, it will be rolled back to the original state if the action
71
+ # fails. *Note* that this will also be the case if an exception is raised
72
+ # while calling the action.
73
+ #
74
+ # === Indirect transitions
75
+ #
76
+ # In addition to the action being run as the _result_ of an event, the action
77
+ # can also be used to run events itself. For example, using the above as an
78
+ # example:
79
+ #
80
+ # vehicle = Vehicle.new # => #<Vehicle:0xb7c27024 @state="parked">
81
+ #
82
+ # vehicle.state_event = 'ignite'
83
+ # vehicle.save # => true
84
+ # vehicle.state # => "idling"
85
+ # vehicle.state_event # => nil
86
+ #
87
+ # As can be seen, the +save+ action automatically invokes the event stored in
88
+ # the +state_event+ attribute (<tt>:ignite</tt> in this case).
89
+ #
90
+ # One important note about using this technique for running transitions is
91
+ # that if the class in which the state machine is defined *also* defines the
92
+ # action being invoked (and not a superclass), then it must manually run the
93
+ # StateMachine hook that checks for event attributes.
94
+ #
95
+ # For example, in ActiveRecord, DataMapper, Mongoid, MongoMapper, and Sequel,
96
+ # the default action (+save+) is already defined in a base class. As a result,
97
+ # when a state machine is defined in a model / resource, StateMachine can
98
+ # automatically hook into the +save+ action.
99
+ #
100
+ # On the other hand, the Vehicle class from above defined its own +save+
101
+ # method (and there is no +save+ method in its superclass). As a result, it
102
+ # must be modified like so:
103
+ #
104
+ # def save
105
+ # self.class.state_machines.transitions(self, :save).perform do
106
+ # @saving_state = state
107
+ # fail != true
108
+ # end
109
+ # end
110
+ #
111
+ # This will add in the functionality for firing the event stored in the
112
+ # +state_event+ attribute.
113
+ #
114
+ # == Callbacks
115
+ #
116
+ # Callbacks are supported for hooking before and after every possible
117
+ # transition in the machine. Each callback is invoked in the order in which
118
+ # it was defined. See StateMachine::Machine#before_transition and
119
+ # StateMachine::Machine#after_transition for documentation on how to define
120
+ # new callbacks.
121
+ #
122
+ # *Note* that callbacks only get executed within the context of an event. As
123
+ # a result, if a class has an initial state when it's created, any callbacks
124
+ # that would normally get executed when the object enters that state will
125
+ # *not* get triggered.
126
+ #
127
+ # For example,
128
+ #
129
+ # class Vehicle
130
+ # state_machine :initial => :parked do
131
+ # after_transition all => :parked do
132
+ # raise ArgumentError
133
+ # end
134
+ # ...
135
+ # end
136
+ # end
137
+ #
138
+ # vehicle = Vehicle.new # => #<Vehicle id: 1, state: "parked">
139
+ # vehicle.save # => true (no exception raised)
140
+ #
141
+ # If you need callbacks to get triggered when an object is created, this
142
+ # should be done by one of the following techniques:
143
+ # * Use a <tt>before :create</tt> or equivalent hook:
144
+ #
145
+ # class Vehicle
146
+ # before :create, :track_initial_transition
147
+ #
148
+ # state_machine do
149
+ # ...
150
+ # end
151
+ # end
152
+ #
153
+ # * Set an initial state and use the correct event to create the
154
+ # object with the proper state, resulting in callbacks being triggered and
155
+ # the object getting persisted (note that the <tt>:pending</tt> state is
156
+ # actually stored as nil):
157
+ #
158
+ # class Vehicle
159
+ # state_machine :initial => :pending
160
+ # after_transition :pending => :parked, :do => :track_initial_transition
161
+ #
162
+ # event :park do
163
+ # transition :pending => :parked
164
+ # end
165
+ #
166
+ # state :pending, :value => nil
167
+ # end
168
+ # end
169
+ #
170
+ # vehicle = Vehicle.new
171
+ # vehicle.park
172
+ #
173
+ # * Use a default event attribute that will automatically trigger when the
174
+ # configured action gets run (note that the <tt>:pending</tt> state is
175
+ # actually stored as nil):
176
+ #
177
+ # class Vehicle < ActiveRecord::Base
178
+ # state_machine :initial => :pending
179
+ # after_transition :pending => :parked, :do => :track_initial_transition
180
+ #
181
+ # event :park do
182
+ # transition :pending => :parked
183
+ # end
184
+ #
185
+ # state :pending, :value => nil
186
+ # end
187
+ #
188
+ # def initialize(*)
189
+ # super
190
+ # self.state_event = 'park'
191
+ # end
192
+ # end
193
+ #
194
+ # vehicle = Vehicle.new
195
+ # vehicle.save
196
+ #
197
+ # === Canceling callbacks
198
+ #
199
+ # Callbacks can be canceled by throwing :halt at any point during the
200
+ # callback. For example,
201
+ #
202
+ # ...
203
+ # throw :halt
204
+ # ...
205
+ #
206
+ # If a +before+ callback halts the chain, the associated transition and all
207
+ # later callbacks are canceled. If an +after+ callback halts the chain,
208
+ # the later callbacks are canceled, but the transition is still successful.
209
+ #
210
+ # These same rules apply to +around+ callbacks with the exception that any
211
+ # +around+ callback that doesn't yield will essentially result in :halt being
212
+ # thrown. Any code executed after the yield will behave in the same way as
213
+ # +after+ callbacks.
214
+ #
215
+ # *Note* that if a +before+ callback fails and the bang version of an event
216
+ # was invoked, an exception will be raised instead of returning false. For
217
+ # example,
218
+ #
219
+ # class Vehicle
220
+ # state_machine :initial => :parked do
221
+ # before_transition any => :idling, :do => lambda {|vehicle| throw :halt}
222
+ # ...
223
+ # end
224
+ # end
225
+ #
226
+ # vehicle = Vehicle.new
227
+ # vehicle.park # => false
228
+ # vehicle.park! # => StateMachine::InvalidTransition: Cannot transition state via :park from "idling"
229
+ #
230
+ # == Observers
231
+ #
232
+ # Observers, in the sense of external classes and *not* Ruby's Observable
233
+ # mechanism, can hook into state machines as well. Such observers use the
234
+ # same callback api that's used internally.
235
+ #
236
+ # Below are examples of defining observers for the following state machine:
237
+ #
238
+ # class Vehicle
239
+ # state_machine do
240
+ # event :park do
241
+ # transition :idling => :parked
242
+ # end
243
+ # ...
244
+ # end
245
+ # ...
246
+ # end
247
+ #
248
+ # Event/Transition behaviors:
249
+ #
250
+ # class VehicleObserver
251
+ # def self.before_park(vehicle, transition)
252
+ # logger.info "#{vehicle} instructed to park... state is: #{transition.from}, state will be: #{transition.to}"
253
+ # end
254
+ #
255
+ # def self.after_park(vehicle, transition, result)
256
+ # logger.info "#{vehicle} instructed to park... state was: #{transition.from}, state is: #{transition.to}"
257
+ # end
258
+ #
259
+ # def self.before_transition(vehicle, transition)
260
+ # logger.info "#{vehicle} instructed to #{transition.event}... #{transition.attribute} is: #{transition.from}, #{transition.attribute} will be: #{transition.to}"
261
+ # end
262
+ #
263
+ # def self.after_transition(vehicle, transition)
264
+ # logger.info "#{vehicle} instructed to #{transition.event}... #{transition.attribute} was: #{transition.from}, #{transition.attribute} is: #{transition.to}"
265
+ # end
266
+ #
267
+ # def self.around_transition(vehicle, transition)
268
+ # logger.info Benchmark.measure { yield }
269
+ # end
270
+ # end
271
+ #
272
+ # Vehicle.state_machine do
273
+ # before_transition :on => :park, :do => VehicleObserver.method(:before_park)
274
+ # before_transition VehicleObserver.method(:before_transition)
275
+ #
276
+ # after_transition :on => :park, :do => VehicleObserver.method(:after_park)
277
+ # after_transition VehicleObserver.method(:after_transition)
278
+ #
279
+ # around_transition VehicleObserver.method(:around_transition)
280
+ # end
281
+ #
282
+ # One common callback is to record transitions for all models in the system
283
+ # for auditing/debugging purposes. Below is an example of an observer that
284
+ # can easily automate this process for all models:
285
+ #
286
+ # class StateMachineObserver
287
+ # def self.before_transition(object, transition)
288
+ # Audit.log_transition(object.attributes)
289
+ # end
290
+ # end
291
+ #
292
+ # [Vehicle, Switch, Project].each do |klass|
293
+ # klass.state_machines.each do |attribute, machine|
294
+ # machine.before_transition StateMachineObserver.method(:before_transition)
295
+ # end
296
+ # end
297
+ #
298
+ # Additional observer-like behavior may be exposed by the various integrations
299
+ # available. See below for more information on integrations.
300
+ #
301
+ # == Overriding instance / class methods
302
+ #
303
+ # Hooking in behavior to the generated instance / class methods from the
304
+ # state machine, events, and states is very simple because of the way these
305
+ # methods are generated on the class. Using the class's ancestors, the
306
+ # original generated method can be referred to via +super+. For example,
307
+ #
308
+ # class Vehicle
309
+ # state_machine do
310
+ # event :park do
311
+ # ...
312
+ # end
313
+ # end
314
+ #
315
+ # def park(*args)
316
+ # logger.info "..."
317
+ # super
318
+ # end
319
+ # end
320
+ #
321
+ # In the above example, the +park+ instance method that's generated on the
322
+ # Vehicle class (by the associated event) is overridden with custom behavior.
323
+ # Once this behavior is complete, the original method from the state machine
324
+ # is invoked by simply calling +super+.
325
+ #
326
+ # The same technique can be used for +state+, +state_name+, and all other
327
+ # instance *and* class methods on the Vehicle class.
328
+ #
329
+ # == Method conflicts
330
+ #
331
+ # By default state_machine does not redefine methods that exist on
332
+ # superclasses (*including* Object) or any modules (*including* Kernel) that
333
+ # were included before it was defined. This is in order to ensure that
334
+ # existing behavior on the class is not broken by the inclusion of
335
+ # state_machine.
336
+ #
337
+ # If a conflicting method is detected, state_machine will generate a warning.
338
+ # For example, consider the following class:
339
+ #
340
+ # class Vehicle
341
+ # state_machine do
342
+ # event :open do
343
+ # ...
344
+ # end
345
+ # end
346
+ # end
347
+ #
348
+ # In the above class, an event named "open" is defined for its state machine.
349
+ # However, "open" is already defined as an instance method in Ruby's Kernel
350
+ # module that gets included in every Object. As a result, state_machine will
351
+ # generate the following warning:
352
+ #
353
+ # Instance method "open" is already defined in Object, use generic helper instead or set StateMachine::Machine.ignore_method_conflicts = true.
354
+ #
355
+ # Even though you may not be using Kernel's implementation of the "open"
356
+ # instance method, state_machine isn't aware of this and, as a result, stays
357
+ # safe and just skips redefining the method.
358
+ #
359
+ # As with almost all helpers methods defined by state_machine in your class,
360
+ # there are generic methods available for working around this method conflict.
361
+ # In the example above, you can invoke the "open" event like so:
362
+ #
363
+ # vehicle = Vehicle.new # => #<Vehicle:0xb72686b4 @state=nil>
364
+ # vehicle.fire_events(:open) # => true
365
+ #
366
+ # # This will not work
367
+ # vehicle.open # => NoMethodError: private method `open' called for #<Vehicle:0xb72686b4 @state=nil>
368
+ #
369
+ # If you want to take on the risk of overriding existing methods and just
370
+ # ignore method conflicts altogether, you can do so by setting the following
371
+ # configuration:
372
+ #
373
+ # StateMachine::Machine.ignore_method_conflicts = true
374
+ #
375
+ # This will allow you to define events like "open" as described above and
376
+ # still generate the "open" instance helper method. For example:
377
+ #
378
+ # StateMachine::Machine.ignore_method_conflicts = true
379
+ #
380
+ # class Vehicle
381
+ # state_machine do
382
+ # event :open do
383
+ # ...
384
+ # end
385
+ # end
386
+ #
387
+ # vehicle = Vehicle.new # => #<Vehicle:0xb72686b4 @state=nil>
388
+ # vehicle.open # => true
389
+ #
390
+ # By default, state_machine helps prevent you from making mistakes and
391
+ # accidentally overriding methods that you didn't intend to. Once you
392
+ # understand this and what the consequences are, setting the
393
+ # +ignore_method_conflicts+ option is a perfectly reasonable workaround.
394
+ #
395
+ # == Integrations
396
+ #
397
+ # By default, state machines are library-agnostic, meaning that they work
398
+ # on any Ruby class and have no external dependencies. However, there are
399
+ # certain libraries which expose additional behavior that can be taken
400
+ # advantage of by state machines.
401
+ #
402
+ # This library is built to work out of the box with a few popular Ruby
403
+ # libraries that allow for additional behavior to provide a cleaner and
404
+ # smoother experience. This is especially the case for objects backed by a
405
+ # database that may allow for transactions, persistent storage,
406
+ # search/filters, callbacks, etc.
407
+ #
408
+ # When a state machine is defined for classes using any of the above libraries,
409
+ # it will try to automatically determine the integration to use (Agnostic,
410
+ # ActiveModel, ActiveRecord, DataMapper, Mongoid, MongoMapper, or Sequel)
411
+ # based on the class definition. To see how each integration affects the
412
+ # machine's behavior, refer to all constants defined under the
413
+ # StateMachine::Integrations namespace.
414
+ class Machine
415
+ include Assertions
416
+ include EvalHelpers
417
+ include MatcherHelpers
418
+
419
+ class << self
420
+ # Attempts to find or create a state machine for the given class. For
421
+ # example,
422
+ #
423
+ # StateMachine::Machine.find_or_create(Vehicle)
424
+ # StateMachine::Machine.find_or_create(Vehicle, :initial => :parked)
425
+ # StateMachine::Machine.find_or_create(Vehicle, :status)
426
+ # StateMachine::Machine.find_or_create(Vehicle, :status, :initial => :parked)
427
+ #
428
+ # If a machine of the given name already exists in one of the class's
429
+ # superclasses, then a copy of that machine will be created and stored
430
+ # in the new owner class (the original will remain unchanged).
431
+ def find_or_create(owner_class, *args, &block)
432
+ options = args.last.is_a?(Hash) ? args.pop : {}
433
+ name = args.first || :state
434
+
435
+ # Find an existing machine
436
+ if owner_class.respond_to?(:state_machines) && machine = owner_class.state_machines[name]
437
+ # Only create a new copy if changes are being made to the machine in
438
+ # a subclass
439
+ if machine.owner_class != owner_class && (options.any? || block_given?)
440
+ machine = machine.clone
441
+ machine.initial_state = options[:initial] if options.include?(:initial)
442
+ machine.owner_class = owner_class
443
+ end
444
+
445
+ # Evaluate DSL
446
+ machine.instance_eval(&block) if block_given?
447
+ else
448
+ # No existing machine: create a new one
449
+ machine = new(owner_class, name, options, &block)
450
+ end
451
+
452
+ machine
453
+ end
454
+
455
+ # Draws the state machines defined in the given classes using GraphViz.
456
+ # The given classes must be a comma-delimited string of class names.
457
+ #
458
+ # Configuration options:
459
+ # * <tt>:file</tt> - A comma-delimited string of files to load that
460
+ # contain the state machine definitions to draw
461
+ # * <tt>:path</tt> - The path to write the graph file to
462
+ # * <tt>:format</tt> - The image format to generate the graph in
463
+ # * <tt>:font</tt> - The name of the font to draw state names in
464
+ def draw(class_names, options = {})
465
+ raise ArgumentError, 'At least one class must be specified' unless class_names && class_names.split(',').any?
466
+
467
+ # Load any files
468
+ if files = options.delete(:file)
469
+ files.split(',').each {|file| require file}
470
+ end
471
+
472
+ class_names.split(',').each do |class_name|
473
+ # Navigate through the namespace structure to get to the class
474
+ klass = Object
475
+ class_name.split('::').each do |name|
476
+ klass = klass.const_defined?(name) ? klass.const_get(name) : klass.const_missing(name)
477
+ end
478
+
479
+ # Draw each of the class's state machines
480
+ klass.state_machines.each_value do |machine|
481
+ machine.draw(options)
482
+ end
483
+ end
484
+ end
485
+ end
486
+
487
+ # Default messages to use for validation errors in ORM integrations
488
+ class << self; attr_accessor :default_messages; end
489
+ @default_messages = {
490
+ :invalid => 'is invalid',
491
+ :invalid_event => 'cannot transition when %s',
492
+ :invalid_transition => 'cannot transition via "%1$s"'
493
+ }
494
+
495
+ # Whether to ignore any conflicts that are detected for helper methods that
496
+ # get generated for a machine's owner class. Default is false.
497
+ class << self; attr_accessor :ignore_method_conflicts; end
498
+ @ignore_method_conflicts = false
499
+
500
+ # The class that the machine is defined in
501
+ attr_reader :owner_class
502
+
503
+ # The name of the machine, used for scoping methods generated for the
504
+ # machine as a whole (not states or events)
505
+ attr_reader :name
506
+
507
+ # The events that trigger transitions. These are sorted, by default, in
508
+ # the order in which they were defined.
509
+ attr_reader :events
510
+
511
+ # A list of all of the states known to this state machine. This will pull
512
+ # states from the following sources:
513
+ # * Initial state
514
+ # * State behaviors
515
+ # * Event transitions (:to, :from, and :except_from options)
516
+ # * Transition callbacks (:to, :from, :except_to, and :except_from options)
517
+ # * Unreferenced states (using +other_states+ helper)
518
+ #
519
+ # These are sorted, by default, in the order in which they were referenced.
520
+ attr_reader :states
521
+
522
+ # The callbacks to invoke before/after a transition is performed
523
+ #
524
+ # Maps :before => callbacks and :after => callbacks
525
+ attr_reader :callbacks
526
+
527
+ # The action to invoke when an object transitions
528
+ attr_reader :action
529
+
530
+ # An identifier that forces all methods (including state predicates and
531
+ # event methods) to be generated with the value prefixed or suffixed,
532
+ # depending on the context.
533
+ attr_reader :namespace
534
+
535
+ # Whether the machine will use transactions when firing events
536
+ attr_reader :use_transactions
537
+
538
+ # Creates a new state machine for the given attribute
539
+ def initialize(owner_class, *args, &block)
540
+ options = args.last.is_a?(Hash) ? args.pop : {}
541
+ assert_valid_keys(options, :attribute, :initial, :initialize, :action, :plural, :namespace, :integration, :messages, :use_transactions)
542
+
543
+ # Find an integration that matches this machine's owner class
544
+ if options.include?(:integration)
545
+ @integration = options[:integration] && StateMachine::Integrations.find_by_name(options[:integration])
546
+ else
547
+ @integration = StateMachine::Integrations.match(owner_class)
548
+ end
549
+
550
+ if @integration
551
+ extend @integration
552
+ options = (@integration.defaults || {}).merge(options)
553
+ end
554
+
555
+ # Add machine-wide defaults
556
+ options = {:use_transactions => true, :initialize => true}.merge(options)
557
+
558
+ # Set machine configuration
559
+ @name = args.first || :state
560
+ @attribute = options[:attribute] || @name
561
+ @events = EventCollection.new(self)
562
+ @states = StateCollection.new(self)
563
+ @callbacks = {:before => [], :after => [], :failure => []}
564
+ @namespace = options[:namespace]
565
+ @messages = options[:messages] || {}
566
+ @action = options[:action]
567
+ @use_transactions = options[:use_transactions]
568
+ @initialize_state = options[:initialize]
569
+ @action_hook_defined = false
570
+ self.owner_class = owner_class
571
+ self.initial_state = options[:initial] unless sibling_machines.any?
572
+
573
+ # Merge with sibling machine configurations
574
+ add_sibling_machine_configs
575
+
576
+ # Define class integration
577
+ define_helpers
578
+ define_scopes(options[:plural])
579
+ after_initialize
580
+
581
+ # Evaluate DSL
582
+ instance_eval(&block) if block_given?
583
+ end
584
+
585
+ # Creates a copy of this machine in addition to copies of each associated
586
+ # event/states/callback, so that the modifications to those collections do
587
+ # not affect the original machine.
588
+ def initialize_copy(orig) #:nodoc:
589
+ super
590
+
591
+ @events = @events.dup
592
+ @events.machine = self
593
+ @states = @states.dup
594
+ @states.machine = self
595
+ @callbacks = {:before => @callbacks[:before].dup, :after => @callbacks[:after].dup, :failure => @callbacks[:failure].dup}
596
+ end
597
+
598
+ # Sets the class which is the owner of this state machine. Any methods
599
+ # generated by states, events, or other parts of the machine will be defined
600
+ # on the given owner class.
601
+ def owner_class=(klass)
602
+ @owner_class = klass
603
+
604
+ # Create modules for extending the class with state/event-specific methods
605
+ @helper_modules = helper_modules = {:instance => HelperModule.new(self, :instance), :class => HelperModule.new(self, :class)}
606
+ owner_class.class_eval do
607
+ extend helper_modules[:class]
608
+ include helper_modules[:instance]
609
+ end
610
+
611
+ # Add class-/instance-level methods to the owner class for state initialization
612
+ unless owner_class < StateMachine::InstanceMethods
613
+ owner_class.class_eval do
614
+ extend StateMachine::ClassMethods
615
+ include StateMachine::InstanceMethods
616
+ end
617
+
618
+ define_state_initializer if @initialize_state
619
+ end
620
+
621
+ # Record this machine as matched to the name in the current owner class.
622
+ # This will override any machines mapped to the same name in any superclasses.
623
+ owner_class.state_machines[name] = self
624
+ end
625
+
626
+ # Sets the initial state of the machine. This can be either the static name
627
+ # of a state or a lambda block which determines the initial state at
628
+ # creation time.
629
+ def initial_state=(new_initial_state)
630
+ @initial_state = new_initial_state
631
+ add_states([@initial_state]) unless dynamic_initial_state?
632
+
633
+ # Update all states to reflect the new initial state
634
+ states.each {|state| state.initial = (state.name == @initial_state)}
635
+
636
+ # Output a warning if there are conflicting initial states for the machine's
637
+ # attribute
638
+ initial_state = states.detect {|state| state.initial}
639
+ if !owner_class_attribute_default.nil? && (dynamic_initial_state? || !owner_class_attribute_default_matches?(initial_state))
640
+ warn(
641
+ "Both #{owner_class.name} and its #{name.inspect} machine have defined "\
642
+ "a different default for \"#{attribute}\". Use only one or the other for "\
643
+ "defining defaults to avoid unexpected behaviors."
644
+ )
645
+ end
646
+ end
647
+
648
+ # Gets the initial state of the machine for the given object. If a dynamic
649
+ # initial state was configured for this machine, then the object will be
650
+ # passed into the lambda block to help determine the actual state.
651
+ #
652
+ # == Examples
653
+ #
654
+ # With a static initial state:
655
+ #
656
+ # class Vehicle
657
+ # state_machine :initial => :parked do
658
+ # ...
659
+ # end
660
+ # end
661
+ #
662
+ # vehicle = Vehicle.new
663
+ # Vehicle.state_machine.initial_state(vehicle) # => #<StateMachine::State name=:parked value="parked" initial=true>
664
+ #
665
+ # With a dynamic initial state:
666
+ #
667
+ # class Vehicle
668
+ # attr_accessor :force_idle
669
+ #
670
+ # state_machine :initial => lambda {|vehicle| vehicle.force_idle ? :idling : :parked} do
671
+ # ...
672
+ # end
673
+ # end
674
+ #
675
+ # vehicle = Vehicle.new
676
+ #
677
+ # vehicle.force_idle = true
678
+ # Vehicle.state_machine.initial_state(vehicle) # => #<StateMachine::State name=:idling value="idling" initial=false>
679
+ #
680
+ # vehicle.force_idle = false
681
+ # Vehicle.state_machine.initial_state(vehicle) # => #<StateMachine::State name=:parked value="parked" initial=false>
682
+ def initial_state(object)
683
+ states.fetch(dynamic_initial_state? ? evaluate_method(object, @initial_state) : @initial_state) if instance_variable_defined?('@initial_state')
684
+ end
685
+
686
+ # Whether a dynamic initial state is being used in the machine
687
+ def dynamic_initial_state?
688
+ instance_variable_defined?('@initial_state') && @initial_state.is_a?(Proc)
689
+ end
690
+
691
+ # Initializes the state on the given object. Initial values are only set if
692
+ # the machine's attribute hasn't been previously initialized.
693
+ #
694
+ # Configuration options:
695
+ # * <tt>:force</tt> - Whether to initialize the state regardless of its
696
+ # current value
697
+ # * <tt>:to</tt> - A hash to set the initial value in instead of writing
698
+ # directly to the object
699
+ def initialize_state(object, options = {})
700
+ state = initial_state(object)
701
+ if state && (options[:force] || initialize_state?(object))
702
+ value = state.value
703
+ object.send "#{attribute}=", value
704
+ end
705
+ end
706
+
707
+ # Gets the actual name of the attribute on the machine's owner class that
708
+ # stores data with the given name.
709
+ def attribute(name = :state)
710
+ name == :state ? @attribute : :"#{self.name}_#{name}"
711
+ end
712
+
713
+ # Defines a new helper method in an instance or class scope with the given
714
+ # name. If the method is already defined in the scope, then this will not
715
+ # override it.
716
+ #
717
+ # If passing in a block, there are two side effects to be aware of
718
+ # 1. The method cannot be chained, meaning that the block cannot call +super+
719
+ # 2. If the method is already defined in an ancestor, then it will not get
720
+ # overridden and a warning will be output.
721
+ #
722
+ # Example:
723
+ #
724
+ # # Instance helper
725
+ # machine.define_helper(:instance, :state_name) do |machine, object|
726
+ # machine.states.match(object).name
727
+ # end
728
+ #
729
+ # # Class helper
730
+ # machine.define_helper(:class, :state_machine_name) do |machine, klass|
731
+ # "State"
732
+ # end
733
+ #
734
+ # You can also define helpers using string evaluation like so:
735
+ #
736
+ # # Instance helper
737
+ # machine.define_helper :instance, <<-end_eval, __FILE__, __LINE__ + 1
738
+ # def state_name
739
+ # self.class.state_machine(:state).states.match(self).name
740
+ # end
741
+ # end_eval
742
+ #
743
+ # # Class helper
744
+ # machine.define_helper :class, <<-end_eval, __FILE__, __LINE__ + 1
745
+ # def state_machine_name
746
+ # "State"
747
+ # end
748
+ # end_eval
749
+ def define_helper(scope, method, *args, &block)
750
+ helper_module = @helper_modules.fetch(scope)
751
+
752
+ if block_given?
753
+ if !self.class.ignore_method_conflicts && conflicting_ancestor = owner_class_ancestor_has_method?(scope, method)
754
+ ancestor_name = conflicting_ancestor.name && !conflicting_ancestor.name.empty? ? conflicting_ancestor.name : conflicting_ancestor.to_s
755
+ warn "#{scope == :class ? 'Class' : 'Instance'} method \"#{method}\" is already defined in #{ancestor_name}, use generic helper instead or set StateMachine::Machine.ignore_method_conflicts = true."
756
+ else
757
+ name = self.name
758
+ helper_module.class_eval do
759
+ define_method(method) do |*block_args|
760
+ block.call((scope == :instance ? self.class : self).state_machine(name), self, *block_args)
761
+ end
762
+ end
763
+ end
764
+ else
765
+ helper_module.class_eval(method, *args)
766
+ end
767
+ end
768
+
769
+ # Customizes the definition of one or more states in the machine.
770
+ #
771
+ # Configuration options:
772
+ # * <tt>:value</tt> - The actual value to store when an object transitions
773
+ # to the state. Default is the name (stringified).
774
+ # * <tt>:cache</tt> - If a dynamic value (via a lambda block) is being used,
775
+ # then setting this to true will cache the evaluated result
776
+ # * <tt>:if</tt> - Determines whether an object's value matches the state
777
+ # (e.g. :value => lambda {Time.now}, :if => lambda {|state| !state.nil?}).
778
+ # By default, the configured value is matched.
779
+ # * <tt>:human_name</tt> - The human-readable version of this state's name.
780
+ # By default, this is either defined by the integration or stringifies the
781
+ # name and converts underscores to spaces.
782
+ #
783
+ # == Customizing the stored value
784
+ #
785
+ # Whenever a state is automatically discovered in the state machine, its
786
+ # default value is assumed to be the stringified version of the name. For
787
+ # example,
788
+ #
789
+ # class Vehicle
790
+ # state_machine :initial => :parked do
791
+ # event :ignite do
792
+ # transition :parked => :idling
793
+ # end
794
+ # end
795
+ # end
796
+ #
797
+ # In the above state machine, there are two states automatically discovered:
798
+ # :parked and :idling. These states, by default, will store their stringified
799
+ # equivalents when an object moves into that state (e.g. "parked" / "idling").
800
+ #
801
+ # For legacy systems or when tying state machines into existing frameworks,
802
+ # it's oftentimes necessary to need to store a different value for a state
803
+ # than the default. In order to continue taking advantage of an expressive
804
+ # state machine and helper methods, every defined state can be re-configured
805
+ # with a custom stored value. For example,
806
+ #
807
+ # class Vehicle
808
+ # state_machine :initial => :parked do
809
+ # event :ignite do
810
+ # transition :parked => :idling
811
+ # end
812
+ #
813
+ # state :idling, :value => 'IDLING'
814
+ # state :parked, :value => 'PARKED
815
+ # end
816
+ # end
817
+ #
818
+ # This is also useful if being used in association with a database and,
819
+ # instead of storing the state name in a column, you want to store the
820
+ # state's foreign key:
821
+ #
822
+ # class VehicleState < ActiveRecord::Base
823
+ # end
824
+ #
825
+ # class Vehicle < ActiveRecord::Base
826
+ # state_machine :attribute => :state_id, :initial => :parked do
827
+ # event :ignite do
828
+ # transition :parked => :idling
829
+ # end
830
+ #
831
+ # states.each do |state|
832
+ # self.state(state.name, :value => lambda { VehicleState.find_by_name(state.name.to_s).id }, :cache => true)
833
+ # end
834
+ # end
835
+ # end
836
+ #
837
+ # In the above example, each known state is configured to store it's
838
+ # associated database id in the +state_id+ attribute. Also, notice that a
839
+ # lambda block is used to define the state's value. This is required in
840
+ # situations (like testing) where the model is loaded without any existing
841
+ # data (i.e. no VehicleState records available).
842
+ #
843
+ # One caveat to the above example is to keep performance in mind. To avoid
844
+ # constant db hits for looking up the VehicleState ids, the value is cached
845
+ # by specifying the <tt>:cache</tt> option. Alternatively, a custom
846
+ # caching strategy can be used like so:
847
+ #
848
+ # class VehicleState < ActiveRecord::Base
849
+ # cattr_accessor :cache_store
850
+ # self.cache_store = ActiveSupport::Cache::MemoryStore.new
851
+ #
852
+ # def self.find_by_name(name)
853
+ # cache_store.fetch(name) { find(:first, :conditions => {:name => name}) }
854
+ # end
855
+ # end
856
+ #
857
+ # === Dynamic values
858
+ #
859
+ # In addition to customizing states with other value types, lambda blocks
860
+ # can also be specified to allow for a state's value to be determined
861
+ # dynamically at runtime. For example,
862
+ #
863
+ # class Vehicle
864
+ # state_machine :purchased_at, :initial => :available do
865
+ # event :purchase do
866
+ # transition all => :purchased
867
+ # end
868
+ #
869
+ # event :restock do
870
+ # transition all => :available
871
+ # end
872
+ #
873
+ # state :available, :value => nil
874
+ # state :purchased, :if => lambda {|value| !value.nil?}, :value => lambda {Time.now}
875
+ # end
876
+ # end
877
+ #
878
+ # In the above definition, the <tt>:purchased</tt> state is customized with
879
+ # both a dynamic value *and* a value matcher.
880
+ #
881
+ # When an object transitions to the purchased state, the value's lambda
882
+ # block will be called. This will get the current time and store it in the
883
+ # object's +purchased_at+ attribute.
884
+ #
885
+ # *Note* that the custom matcher is very important here. Since there's no
886
+ # way for the state machine to figure out an object's state when it's set to
887
+ # a runtime value, it must be explicitly defined. If the <tt>:if</tt> option
888
+ # were not configured for the state, then an ArgumentError exception would
889
+ # be raised at runtime, indicating that the state machine could not figure
890
+ # out what the current state of the object was.
891
+ #
892
+ # == Behaviors
893
+ #
894
+ # Behaviors define a series of methods to mixin with objects when the current
895
+ # state matches the given one(s). This allows instance methods to behave
896
+ # a specific way depending on what the value of the object's state is.
897
+ #
898
+ # For example,
899
+ #
900
+ # class Vehicle
901
+ # attr_accessor :driver
902
+ # attr_accessor :passenger
903
+ #
904
+ # state_machine :initial => :parked do
905
+ # event :ignite do
906
+ # transition :parked => :idling
907
+ # end
908
+ #
909
+ # state :parked do
910
+ # def speed
911
+ # 0
912
+ # end
913
+ #
914
+ # def rotate_driver
915
+ # driver = self.driver
916
+ # self.driver = passenger
917
+ # self.passenger = driver
918
+ # true
919
+ # end
920
+ # end
921
+ #
922
+ # state :idling, :first_gear do
923
+ # def speed
924
+ # 20
925
+ # end
926
+ #
927
+ # def rotate_driver
928
+ # self.state = 'parked'
929
+ # rotate_driver
930
+ # end
931
+ # end
932
+ #
933
+ # other_states :backing_up
934
+ # end
935
+ # end
936
+ #
937
+ # In the above example, there are two dynamic behaviors defined for the
938
+ # class:
939
+ # * +speed+
940
+ # * +rotate_driver+
941
+ #
942
+ # Each of these behaviors are instance methods on the Vehicle class. However,
943
+ # which method actually gets invoked is based on the current state of the
944
+ # object. Using the above class as the example:
945
+ #
946
+ # vehicle = Vehicle.new
947
+ # vehicle.driver = 'John'
948
+ # vehicle.passenger = 'Jane'
949
+ #
950
+ # # Behaviors in the "parked" state
951
+ # vehicle.state # => "parked"
952
+ # vehicle.speed # => 0
953
+ # vehicle.rotate_driver # => true
954
+ # vehicle.driver # => "Jane"
955
+ # vehicle.passenger # => "John"
956
+ #
957
+ # vehicle.ignite # => true
958
+ #
959
+ # # Behaviors in the "idling" state
960
+ # vehicle.state # => "idling"
961
+ # vehicle.speed # => 20
962
+ # vehicle.rotate_driver # => true
963
+ # vehicle.driver # => "John"
964
+ # vehicle.passenger # => "Jane"
965
+ #
966
+ # As can be seen, both the +speed+ and +rotate_driver+ instance method
967
+ # implementations changed how they behave based on what the current state
968
+ # of the vehicle was.
969
+ #
970
+ # === Invalid behaviors
971
+ #
972
+ # If a specific behavior has not been defined for a state, then a
973
+ # NoMethodError exception will be raised, indicating that that method would
974
+ # not normally exist for an object with that state.
975
+ #
976
+ # Using the example from before:
977
+ #
978
+ # vehicle = Vehicle.new
979
+ # vehicle.state = 'backing_up'
980
+ # vehicle.speed # => NoMethodError: undefined method 'speed' for #<Vehicle:0xb7d296ac> in state "backing_up"
981
+ #
982
+ # === Using matchers
983
+ #
984
+ # The +all+ / +any+ matchers can be used to easily define behaviors for a
985
+ # group of states. Note, however, that you cannot use these matchers to
986
+ # set configurations for states. Behaviors using these matchers can be
987
+ # defined at any point in the state machine and will always get applied to
988
+ # the proper states.
989
+ #
990
+ # For example:
991
+ #
992
+ # state_machine :initial => :parked do
993
+ # ...
994
+ #
995
+ # state all - [:parked, :idling, :stalled] do
996
+ # validates_presence_of :speed
997
+ #
998
+ # def speed
999
+ # gear * 10
1000
+ # end
1001
+ # end
1002
+ # end
1003
+ #
1004
+ # == State-aware class methods
1005
+ #
1006
+ # In addition to defining scopes for instance methods that are state-aware,
1007
+ # the same can be done for certain types of class methods.
1008
+ #
1009
+ # Some libraries have support for class-level methods that only run certain
1010
+ # behaviors based on a conditions hash passed in. For example:
1011
+ #
1012
+ # class Vehicle < ActiveRecord::Base
1013
+ # state_machine do
1014
+ # ...
1015
+ # state :first_gear, :second_gear, :third_gear do
1016
+ # validates_presence_of :speed
1017
+ # validates_inclusion_of :speed, :in => 0..25, :if => :in_school_zone?
1018
+ # end
1019
+ # end
1020
+ # end
1021
+ #
1022
+ # In the above ActiveRecord model, two validations have been defined which
1023
+ # will *only* run when the Vehicle object is in one of the three states:
1024
+ # +first_gear+, +second_gear+, or +third_gear. Notice, also, that if/unless
1025
+ # conditions can continue to be used.
1026
+ #
1027
+ # This functionality is not library-specific and can work for any class-level
1028
+ # method that is defined like so:
1029
+ #
1030
+ # def validates_presence_of(attribute, options = {})
1031
+ # ...
1032
+ # end
1033
+ #
1034
+ # The minimum requirement is that the last argument in the method be an
1035
+ # options hash which contains at least <tt>:if</tt> condition support.
1036
+ def state(*names, &block)
1037
+ options = names.last.is_a?(Hash) ? names.pop : {}
1038
+ assert_valid_keys(options, :value, :cache, :if, :human_name)
1039
+
1040
+ # Store the context so that it can be used for / matched against any state
1041
+ # that gets added
1042
+ @states.context(names, &block) if block_given?
1043
+
1044
+ if names.first.is_a?(Matcher)
1045
+ # Add any states referenced in the matcher. When matchers are used,
1046
+ # states are not allowed to be configured.
1047
+ raise ArgumentError, "Cannot configure states when using matchers (using #{options.inspect})" if options.any?
1048
+ states = add_states(names.first.values)
1049
+ else
1050
+ states = add_states(names)
1051
+
1052
+ # Update the configuration for the state(s)
1053
+ states.each do |state|
1054
+ if options.include?(:value)
1055
+ state.value = options[:value]
1056
+ self.states.update(state)
1057
+ end
1058
+
1059
+ state.human_name = options[:human_name] if options.include?(:human_name)
1060
+ state.cache = options[:cache] if options.include?(:cache)
1061
+ state.matcher = options[:if] if options.include?(:if)
1062
+ end
1063
+ end
1064
+
1065
+ states.length == 1 ? states.first : states
1066
+ end
1067
+ alias_method :other_states, :state
1068
+
1069
+ # Gets the current value stored in the given object's attribute.
1070
+ #
1071
+ # For example,
1072
+ #
1073
+ # class Vehicle
1074
+ # state_machine :initial => :parked do
1075
+ # ...
1076
+ # end
1077
+ # end
1078
+ #
1079
+ # vehicle = Vehicle.new # => #<Vehicle:0xb7d94ab0 @state="parked">
1080
+ # Vehicle.state_machine.read(vehicle, :state) # => "parked" # Equivalent to vehicle.state
1081
+ # Vehicle.state_machine.read(vehicle, :event) # => nil # Equivalent to vehicle.state_event
1082
+ def read(object, attribute, ivar = false)
1083
+ attribute = self.attribute(attribute)
1084
+ if ivar
1085
+ object.instance_variable_defined?("@#{attribute}") ? object.instance_variable_get("@#{attribute}") : nil
1086
+ else
1087
+ object.send(attribute)
1088
+ end
1089
+ end
1090
+
1091
+ # Sets a new value in the given object's attribute.
1092
+ #
1093
+ # For example,
1094
+ #
1095
+ # class Vehicle
1096
+ # state_machine :initial => :parked do
1097
+ # ...
1098
+ # end
1099
+ # end
1100
+ #
1101
+ # vehicle = Vehicle.new # => #<Vehicle:0xb7d94ab0 @state="parked">
1102
+ # Vehicle.state_machine.write(vehicle, :state, 'idling') # => Equivalent to vehicle.state = 'idling'
1103
+ # Vehicle.state_machine.write(vehicle, :event, 'park') # => Equivalent to vehicle.state_event = 'park'
1104
+ # vehicle.state # => "idling"
1105
+ # vehicle.event # => "park"
1106
+ def write(object, attribute, value, ivar = false)
1107
+ attribute = self.attribute(attribute)
1108
+ ivar ? object.instance_variable_set("@#{attribute}", value) : object.send("#{attribute}=", value)
1109
+ end
1110
+
1111
+ # Defines one or more events for the machine and the transitions that can
1112
+ # be performed when those events are run.
1113
+ #
1114
+ # This method is also aliased as +on+ for improved compatibility with
1115
+ # using a domain-specific language.
1116
+ #
1117
+ # Configuration options:
1118
+ # * <tt>:human_name</tt> - The human-readable version of this event's name.
1119
+ # By default, this is either defined by the integration or stringifies the
1120
+ # name and converts underscores to spaces.
1121
+ #
1122
+ # == Instance methods
1123
+ #
1124
+ # The following instance methods are generated when a new event is defined
1125
+ # (the "park" event is used as an example):
1126
+ # * <tt>park(..., run_action = true)</tt> - Fires the "park" event,
1127
+ # transitioning from the current state to the next valid state. If the
1128
+ # last argument is a boolean, it will control whether the machine's action
1129
+ # gets run.
1130
+ # * <tt>park!(..., run_action = true)</tt> - Fires the "park" event,
1131
+ # transitioning from the current state to the next valid state. If the
1132
+ # transition fails, then a StateMachine::InvalidTransition error will be
1133
+ # raised. If the last argument is a boolean, it will control whether the
1134
+ # machine's action gets run.
1135
+ # * <tt>can_park?(requirements = {})</tt> - Checks whether the "park" event
1136
+ # can be fired given the current state of the object. This will *not* run
1137
+ # validations or callbacks in ORM integrations. It will only determine if
1138
+ # the state machine defines a valid transition for the event. To check
1139
+ # whether an event can fire *and* passes validations, use event attributes
1140
+ # (e.g. state_event) as described in the "Events" documentation of each
1141
+ # ORM integration.
1142
+ # * <tt>park_transition(requirements = {})</tt> - Gets the next transition
1143
+ # that would be performed if the "park" event were to be fired now on the
1144
+ # object or nil if no transitions can be performed. Like <tt>can_park?</tt>
1145
+ # this will also *not* run validations or callbacks. It will only
1146
+ # determine if the state machine defines a valid transition for the event.
1147
+ #
1148
+ # With a namespace of "car", the above names map to the following methods:
1149
+ # * <tt>can_park_car?</tt>
1150
+ # * <tt>park_car_transition</tt>
1151
+ # * <tt>park_car</tt>
1152
+ # * <tt>park_car!</tt>
1153
+ #
1154
+ # The <tt>can_park?</tt> and <tt>park_transition</tt> helpers both take an
1155
+ # optional set of requirements for determining what transitions are available
1156
+ # for the current object. These requirements include:
1157
+ # * <tt>:from</tt> - One or more states to transition from. If none are
1158
+ # specified, then this will be the object's current state.
1159
+ # * <tt>:to</tt> - One or more states to transition to. If none are
1160
+ # specified, then this will match any to state.
1161
+ # * <tt>:guard</tt> - Whether to guard transitions with the if/unless
1162
+ # conditionals defined for each one. Default is true.
1163
+ #
1164
+ # == Defining transitions
1165
+ #
1166
+ # +event+ requires a block which allows you to define the possible
1167
+ # transitions that can happen as a result of that event. For example,
1168
+ #
1169
+ # event :park, :stop do
1170
+ # transition :idling => :parked
1171
+ # end
1172
+ #
1173
+ # event :first_gear do
1174
+ # transition :parked => :first_gear, :if => :seatbelt_on?
1175
+ # transition :parked => same # Allow to loopback if seatbelt is off
1176
+ # end
1177
+ #
1178
+ # See StateMachine::Event#transition for more information on
1179
+ # the possible options that can be passed in.
1180
+ #
1181
+ # *Note* that this block is executed within the context of the actual event
1182
+ # object. As a result, you will not be able to reference any class methods
1183
+ # on the model without referencing the class itself. For example,
1184
+ #
1185
+ # class Vehicle
1186
+ # def self.safe_states
1187
+ # [:parked, :idling, :stalled]
1188
+ # end
1189
+ #
1190
+ # state_machine do
1191
+ # event :park do
1192
+ # transition Vehicle.safe_states => :parked
1193
+ # end
1194
+ # end
1195
+ # end
1196
+ #
1197
+ # == Overriding the event method
1198
+ #
1199
+ # By default, this will define an instance method (with the same name as the
1200
+ # event) that will fire the next possible transition for that. Although the
1201
+ # +before_transition+, +after_transition+, and +around_transition+ hooks
1202
+ # allow you to define behavior that gets executed as a result of the event's
1203
+ # transition, you can also override the event method in order to have a
1204
+ # little more fine-grained control.
1205
+ #
1206
+ # For example:
1207
+ #
1208
+ # class Vehicle
1209
+ # state_machine do
1210
+ # event :park do
1211
+ # ...
1212
+ # end
1213
+ # end
1214
+ #
1215
+ # def park(*)
1216
+ # take_deep_breath # Executes before the transition (and before_transition hooks) even if no transition is possible
1217
+ # if result = super # Runs the transition and all before/after/around hooks
1218
+ # applaud # Executes after the transition (and after_transition hooks)
1219
+ # end
1220
+ # result
1221
+ # end
1222
+ # end
1223
+ #
1224
+ # There are a few important things to note here. First, the method
1225
+ # signature is defined with an unlimited argument list in order to allow
1226
+ # callers to continue passing arguments that are expected by state_machine.
1227
+ # For example, it will still allow calls to +park+ with a single parameter
1228
+ # for skipping the configured action.
1229
+ #
1230
+ # Second, the overridden event method must call +super+ in order to run the
1231
+ # logic for running the next possible transition. In order to remain
1232
+ # consistent with other events, the result of +super+ is returned.
1233
+ #
1234
+ # Third, any behavior defined in this method will *not* get executed if
1235
+ # you're taking advantage of attribute-based event transitions. For example:
1236
+ #
1237
+ # vehicle = Vehicle.new
1238
+ # vehicle.state_event = 'park'
1239
+ # vehicle.save
1240
+ #
1241
+ # In this case, the +park+ event will run the before/after/around transition
1242
+ # hooks and transition the state, but the behavior defined in the overriden
1243
+ # +park+ method will *not* be executed.
1244
+ #
1245
+ # == Defining additional arguments
1246
+ #
1247
+ # Additional arguments can be passed into events and accessed by transition
1248
+ # hooks like so:
1249
+ #
1250
+ # class Vehicle
1251
+ # state_machine do
1252
+ # after_transition :on => :park do |vehicle, transition|
1253
+ # kind = *transition.args # :parallel
1254
+ # ...
1255
+ # end
1256
+ # after_transition :on => :park, :do => :take_deep_breath
1257
+ #
1258
+ # event :park do
1259
+ # ...
1260
+ # end
1261
+ #
1262
+ # def take_deep_breath(transition)
1263
+ # kind = *transition.args # :parallel
1264
+ # ...
1265
+ # end
1266
+ # end
1267
+ # end
1268
+ #
1269
+ # vehicle = Vehicle.new
1270
+ # vehicle.park(:parallel)
1271
+ #
1272
+ # *Remember* that if the last argument is a boolean, it will be used as the
1273
+ # +run_action+ parameter to the event action. Using the +park+ action
1274
+ # example from above, you can might call it like so:
1275
+ #
1276
+ # vehicle.park # => Uses default args and runs machine action
1277
+ # vehicle.park(:parallel) # => Specifies the +kind+ argument and runs the machine action
1278
+ # vehicle.park(:parallel, false) # => Specifies the +kind+ argument and *skips* the machine action
1279
+ #
1280
+ # If you decide to override the +park+ event method *and* define additional
1281
+ # arguments, you can do so as shown below:
1282
+ #
1283
+ # class Vehicle
1284
+ # state_machine do
1285
+ # event :park do
1286
+ # ...
1287
+ # end
1288
+ # end
1289
+ #
1290
+ # def park(kind = :parallel, *args)
1291
+ # take_deep_breath if kind == :parallel
1292
+ # super
1293
+ # end
1294
+ # end
1295
+ #
1296
+ # Note that +super+ is called instead of <tt>super(*args)</tt>. This allow
1297
+ # the entire arguments list to be accessed by transition callbacks through
1298
+ # StateMachine::Transition#args.
1299
+ #
1300
+ # === Using matchers
1301
+ #
1302
+ # The +all+ / +any+ matchers can be used to easily execute blocks for a
1303
+ # group of events. Note, however, that you cannot use these matchers to
1304
+ # set configurations for events. Blocks using these matchers can be
1305
+ # defined at any point in the state machine and will always get applied to
1306
+ # the proper events.
1307
+ #
1308
+ # For example:
1309
+ #
1310
+ # state_machine :initial => :parked do
1311
+ # ...
1312
+ #
1313
+ # event all - [:crash] do
1314
+ # transition :stalled => :parked
1315
+ # end
1316
+ # end
1317
+ #
1318
+ # == Example
1319
+ #
1320
+ # class Vehicle
1321
+ # state_machine do
1322
+ # # The park, stop, and halt events will all share the given transitions
1323
+ # event :park, :stop, :halt do
1324
+ # transition [:idling, :backing_up] => :parked
1325
+ # end
1326
+ #
1327
+ # event :stop do
1328
+ # transition :first_gear => :idling
1329
+ # end
1330
+ #
1331
+ # event :ignite do
1332
+ # transition :parked => :idling
1333
+ # transition :idling => same # Allow ignite while still idling
1334
+ # end
1335
+ # end
1336
+ # end
1337
+ def event(*names, &block)
1338
+ options = names.last.is_a?(Hash) ? names.pop : {}
1339
+ assert_valid_keys(options, :human_name)
1340
+
1341
+ # Store the context so that it can be used for / matched against any event
1342
+ # that gets added
1343
+ @events.context(names, &block) if block_given?
1344
+
1345
+ if names.first.is_a?(Matcher)
1346
+ # Add any events referenced in the matcher. When matchers are used,
1347
+ # events are not allowed to be configured.
1348
+ raise ArgumentError, "Cannot configure events when using matchers (using #{options.inspect})" if options.any?
1349
+ events = add_events(names.first.values)
1350
+ else
1351
+ events = add_events(names)
1352
+
1353
+ # Update the configuration for the event(s)
1354
+ events.each do |event|
1355
+ event.human_name = options[:human_name] if options.include?(:human_name)
1356
+
1357
+ # Add any states that may have been referenced within the event
1358
+ add_states(event.known_states)
1359
+ end
1360
+ end
1361
+
1362
+ events.length == 1 ? events.first : events
1363
+ end
1364
+ alias_method :on, :event
1365
+
1366
+ # Creates a new transition that determines what to change the current state
1367
+ # to when an event fires.
1368
+ #
1369
+ # == Defining transitions
1370
+ #
1371
+ # The options for a new transition uses the Hash syntax to map beginning
1372
+ # states to ending states. For example,
1373
+ #
1374
+ # transition :parked => :idling, :idling => :first_gear, :on => :ignite
1375
+ #
1376
+ # In this case, when the +ignite+ event is fired, this transition will cause
1377
+ # the state to be +idling+ if it's current state is +parked+ or +first_gear+
1378
+ # if it's current state is +idling+.
1379
+ #
1380
+ # To help define these implicit transitions, a set of helpers are available
1381
+ # for slightly more complex matching:
1382
+ # * <tt>all</tt> - Matches every state in the machine
1383
+ # * <tt>all - [:parked, :idling, ...]</tt> - Matches every state except those specified
1384
+ # * <tt>any</tt> - An alias for +all+ (matches every state in the machine)
1385
+ # * <tt>same</tt> - Matches the same state being transitioned from
1386
+ #
1387
+ # See StateMachine::MatcherHelpers for more information.
1388
+ #
1389
+ # Examples:
1390
+ #
1391
+ # transition all => nil, :on => :ignite # Transitions to nil regardless of the current state
1392
+ # transition all => :idling, :on => :ignite # Transitions to :idling regardless of the current state
1393
+ # transition all - [:idling, :first_gear] => :idling, :on => :ignite # Transitions every state but :idling and :first_gear to :idling
1394
+ # transition nil => :idling, :on => :ignite # Transitions to :idling from the nil state
1395
+ # transition :parked => :idling, :on => :ignite # Transitions to :idling if :parked
1396
+ # transition [:parked, :stalled] => :idling, :on => :ignite # Transitions to :idling if :parked or :stalled
1397
+ #
1398
+ # transition :parked => same, :on => :park # Loops :parked back to :parked
1399
+ # transition [:parked, :stalled] => same, :on => [:park, :stall] # Loops either :parked or :stalled back to the same state on the park and stall events
1400
+ # transition all - :parked => same, :on => :noop # Loops every state but :parked back to the same state
1401
+ #
1402
+ # # Transitions to :idling if :parked, :first_gear if :idling, or :second_gear if :first_gear
1403
+ # transition :parked => :idling, :idling => :first_gear, :first_gear => :second_gear, :on => :shift_up
1404
+ #
1405
+ # == Verbose transitions
1406
+ #
1407
+ # Transitions can also be defined use an explicit set of configuration
1408
+ # options:
1409
+ # * <tt>:from</tt> - A state or array of states that can be transitioned from.
1410
+ # If not specified, then the transition can occur for *any* state.
1411
+ # * <tt>:to</tt> - The state that's being transitioned to. If not specified,
1412
+ # then the transition will simply loop back (i.e. the state will not change).
1413
+ # * <tt>:except_from</tt> - A state or array of states that *cannot* be
1414
+ # transitioned from.
1415
+ #
1416
+ # These options must be used when defining transitions within the context
1417
+ # of a state.
1418
+ #
1419
+ # Examples:
1420
+ #
1421
+ # transition :to => nil, :on => :park
1422
+ # transition :to => :idling, :on => :ignite
1423
+ # transition :except_from => [:idling, :first_gear], :to => :idling, :on => :ignite
1424
+ # transition :from => nil, :to => :idling, :on => :ignite
1425
+ # transition :from => [:parked, :stalled], :to => :idling, :on => :ignite
1426
+ #
1427
+ # == Conditions
1428
+ #
1429
+ # In addition to the state requirements for each transition, a condition
1430
+ # can also be defined to help determine whether that transition is
1431
+ # available. These options will work on both the normal and verbose syntax.
1432
+ #
1433
+ # Configuration options:
1434
+ # * <tt>:if</tt> - A method, proc or string to call to determine if the
1435
+ # transition should occur (e.g. :if => :moving?, or :if => lambda {|vehicle| vehicle.speed > 60}).
1436
+ # The condition should return or evaluate to true or false.
1437
+ # * <tt>:unless</tt> - A method, proc or string to call to determine if the
1438
+ # transition should not occur (e.g. :unless => :stopped?, or :unless => lambda {|vehicle| vehicle.speed <= 60}).
1439
+ # The condition should return or evaluate to true or false.
1440
+ #
1441
+ # Examples:
1442
+ #
1443
+ # transition :parked => :idling, :on => :ignite, :if => :moving?
1444
+ # transition :parked => :idling, :on => :ignite, :unless => :stopped?
1445
+ # transition :idling => :first_gear, :first_gear => :second_gear, :on => :shift_up, :if => :seatbelt_on?
1446
+ #
1447
+ # transition :from => :parked, :to => :idling, :on => ignite, :if => :moving?
1448
+ # transition :from => :parked, :to => :idling, :on => ignite, :unless => :stopped?
1449
+ #
1450
+ # == Order of operations
1451
+ #
1452
+ # Transitions are evaluated in the order in which they're defined. As a
1453
+ # result, if more than one transition applies to a given object, then the
1454
+ # first transition that matches will be performed.
1455
+ def transition(options)
1456
+ raise ArgumentError, 'Must specify :on event' unless options[:on]
1457
+
1458
+ branches = []
1459
+ options = options.dup
1460
+ event(*Array(options.delete(:on))) { branches << transition(options) }
1461
+
1462
+ branches.length == 1 ? branches.first : branches
1463
+ end
1464
+
1465
+ # Creates a callback that will be invoked *before* a transition is
1466
+ # performed so long as the given requirements match the transition.
1467
+ #
1468
+ # == The callback
1469
+ #
1470
+ # Callbacks must be defined as either an argument, in the :do option, or
1471
+ # as a block. For example,
1472
+ #
1473
+ # class Vehicle
1474
+ # state_machine do
1475
+ # before_transition :set_alarm
1476
+ # before_transition :set_alarm, all => :parked
1477
+ # before_transition all => :parked, :do => :set_alarm
1478
+ # before_transition all => :parked do |vehicle, transition|
1479
+ # vehicle.set_alarm
1480
+ # end
1481
+ # ...
1482
+ # end
1483
+ # end
1484
+ #
1485
+ # Notice that the first three callbacks are the same in terms of how the
1486
+ # methods to invoke are defined. However, using the <tt>:do</tt> can
1487
+ # provide for a more fluid DSL.
1488
+ #
1489
+ # In addition, multiple callbacks can be defined like so:
1490
+ #
1491
+ # class Vehicle
1492
+ # state_machine do
1493
+ # before_transition :set_alarm, :lock_doors, all => :parked
1494
+ # before_transition all => :parked, :do => [:set_alarm, :lock_doors]
1495
+ # before_transition :set_alarm do |vehicle, transition|
1496
+ # vehicle.lock_doors
1497
+ # end
1498
+ # end
1499
+ # end
1500
+ #
1501
+ # Notice that the different ways of configuring methods can be mixed.
1502
+ #
1503
+ # == State requirements
1504
+ #
1505
+ # Callbacks can require that the machine be transitioning from and to
1506
+ # specific states. These requirements use a Hash syntax to map beginning
1507
+ # states to ending states. For example,
1508
+ #
1509
+ # before_transition :parked => :idling, :idling => :first_gear, :do => :set_alarm
1510
+ #
1511
+ # In this case, the +set_alarm+ callback will only be called if the machine
1512
+ # is transitioning from +parked+ to +idling+ or from +idling+ to +parked+.
1513
+ #
1514
+ # To help define state requirements, a set of helpers are available for
1515
+ # slightly more complex matching:
1516
+ # * <tt>all</tt> - Matches every state/event in the machine
1517
+ # * <tt>all - [:parked, :idling, ...]</tt> - Matches every state/event except those specified
1518
+ # * <tt>any</tt> - An alias for +all+ (matches every state/event in the machine)
1519
+ # * <tt>same</tt> - Matches the same state being transitioned from
1520
+ #
1521
+ # See StateMachine::MatcherHelpers for more information.
1522
+ #
1523
+ # Examples:
1524
+ #
1525
+ # before_transition :parked => [:idling, :first_gear], :do => ... # Matches from parked to idling or first_gear
1526
+ # before_transition all - [:parked, :idling] => :idling, :do => ... # Matches from every state except parked and idling to idling
1527
+ # before_transition all => :parked, :do => ... # Matches all states to parked
1528
+ # before_transition any => same, :do => ... # Matches every loopback
1529
+ #
1530
+ # == Event requirements
1531
+ #
1532
+ # In addition to state requirements, an event requirement can be defined so
1533
+ # that the callback is only invoked on specific events using the +on+
1534
+ # option. This can also use the same matcher helpers as the state
1535
+ # requirements.
1536
+ #
1537
+ # Examples:
1538
+ #
1539
+ # before_transition :on => :ignite, :do => ... # Matches only on ignite
1540
+ # before_transition :on => all - :ignite, :do => ... # Matches on every event except ignite
1541
+ # before_transition :parked => :idling, :on => :ignite, :do => ... # Matches from parked to idling on ignite
1542
+ #
1543
+ # == Verbose Requirements
1544
+ #
1545
+ # Requirements can also be defined using verbose options rather than the
1546
+ # implicit Hash syntax and helper methods described above.
1547
+ #
1548
+ # Configuration options:
1549
+ # * <tt>:from</tt> - One or more states being transitioned from. If none
1550
+ # are specified, then all states will match.
1551
+ # * <tt>:to</tt> - One or more states being transitioned to. If none are
1552
+ # specified, then all states will match.
1553
+ # * <tt>:on</tt> - One or more events that fired the transition. If none
1554
+ # are specified, then all events will match.
1555
+ # * <tt>:except_from</tt> - One or more states *not* being transitioned from
1556
+ # * <tt>:except_to</tt> - One more states *not* being transitioned to
1557
+ # * <tt>:except_on</tt> - One or more events that *did not* fire the transition
1558
+ #
1559
+ # Examples:
1560
+ #
1561
+ # before_transition :from => :ignite, :to => :idling, :on => :park, :do => ...
1562
+ # before_transition :except_from => :ignite, :except_to => :idling, :except_on => :park, :do => ...
1563
+ #
1564
+ # == Conditions
1565
+ #
1566
+ # In addition to the state/event requirements, a condition can also be
1567
+ # defined to help determine whether the callback should be invoked.
1568
+ #
1569
+ # Configuration options:
1570
+ # * <tt>:if</tt> - A method, proc or string to call to determine if the
1571
+ # callback should occur (e.g. :if => :allow_callbacks, or
1572
+ # :if => lambda {|user| user.signup_step > 2}). The method, proc or string
1573
+ # should return or evaluate to a true or false value.
1574
+ # * <tt>:unless</tt> - A method, proc or string to call to determine if the
1575
+ # callback should not occur (e.g. :unless => :skip_callbacks, or
1576
+ # :unless => lambda {|user| user.signup_step <= 2}). The method, proc or
1577
+ # string should return or evaluate to a true or false value.
1578
+ #
1579
+ # Examples:
1580
+ #
1581
+ # before_transition :parked => :idling, :if => :moving?, :do => ...
1582
+ # before_transition :on => :ignite, :unless => :seatbelt_on?, :do => ...
1583
+ #
1584
+ # == Accessing the transition
1585
+ #
1586
+ # In addition to passing the object being transitioned, the actual
1587
+ # transition describing the context (e.g. event, from, to) can be accessed
1588
+ # as well. This additional argument is only passed if the callback allows
1589
+ # for it.
1590
+ #
1591
+ # For example,
1592
+ #
1593
+ # class Vehicle
1594
+ # # Only specifies one parameter (the object being transitioned)
1595
+ # before_transition all => :parked do |vehicle|
1596
+ # vehicle.set_alarm
1597
+ # end
1598
+ #
1599
+ # # Specifies 2 parameters (object being transitioned and actual transition)
1600
+ # before_transition all => :parked do |vehicle, transition|
1601
+ # vehicle.set_alarm(transition)
1602
+ # end
1603
+ # end
1604
+ #
1605
+ # *Note* that the object in the callback will only be passed in as an
1606
+ # argument if callbacks are configured to *not* be bound to the object
1607
+ # involved. This is the default and may change on a per-integration basis.
1608
+ #
1609
+ # See StateMachine::Transition for more information about the
1610
+ # attributes available on the transition.
1611
+ #
1612
+ # == Usage with delegates
1613
+ #
1614
+ # As noted above, state_machine uses the callback method's argument list
1615
+ # arity to determine whether to include the transition in the method call.
1616
+ # If you're using delegates, such as those defined in ActiveSupport or
1617
+ # Forwardable, the actual arity of the delegated method gets masked. This
1618
+ # means that callbacks which reference delegates will always get passed the
1619
+ # transition as an argument. For example:
1620
+ #
1621
+ # class Vehicle
1622
+ # extend Forwardable
1623
+ # delegate :refresh => :dashboard
1624
+ #
1625
+ # state_machine do
1626
+ # before_transition :refresh
1627
+ # ...
1628
+ # end
1629
+ #
1630
+ # def dashboard
1631
+ # @dashboard ||= Dashboard.new
1632
+ # end
1633
+ # end
1634
+ #
1635
+ # class Dashboard
1636
+ # def refresh(transition)
1637
+ # # ...
1638
+ # end
1639
+ # end
1640
+ #
1641
+ # In the above example, <tt>Dashboard#refresh</tt> *must* defined a
1642
+ # +transition+ argument. Otherwise, an +ArgumentError+ exception will get
1643
+ # raised. The only way around this is to avoid the use of delegates and
1644
+ # manually define the delegate method so that the correct arity is used.
1645
+ #
1646
+ # == Examples
1647
+ #
1648
+ # Below is an example of a class with one state machine and various types
1649
+ # of +before+ transitions defined for it:
1650
+ #
1651
+ # class Vehicle
1652
+ # state_machine do
1653
+ # # Before all transitions
1654
+ # before_transition :update_dashboard
1655
+ #
1656
+ # # Before specific transition:
1657
+ # before_transition [:first_gear, :idling] => :parked, :on => :park, :do => :take_off_seatbelt
1658
+ #
1659
+ # # With conditional callback:
1660
+ # before_transition all => :parked, :do => :take_off_seatbelt, :if => :seatbelt_on?
1661
+ #
1662
+ # # Using helpers:
1663
+ # before_transition all - :stalled => same, :on => any - :crash, :do => :update_dashboard
1664
+ # ...
1665
+ # end
1666
+ # end
1667
+ #
1668
+ # As can be seen, any number of transitions can be created using various
1669
+ # combinations of configuration options.
1670
+ def before_transition(*args, &block)
1671
+ options = (args.last.is_a?(Hash) ? args.pop : {})
1672
+ options[:do] = args if args.any?
1673
+ add_callback(:before, options, &block)
1674
+ end
1675
+
1676
+ # Creates a callback that will be invoked *after* a transition is
1677
+ # performed so long as the given requirements match the transition.
1678
+ #
1679
+ # See +before_transition+ for a description of the possible configurations
1680
+ # for defining callbacks.
1681
+ def after_transition(*args, &block)
1682
+ options = (args.last.is_a?(Hash) ? args.pop : {})
1683
+ options[:do] = args if args.any?
1684
+ add_callback(:after, options, &block)
1685
+ end
1686
+
1687
+ # Creates a callback that will be invoked *around* a transition so long as
1688
+ # the given requirements match the transition.
1689
+ #
1690
+ # == The callback
1691
+ #
1692
+ # Around callbacks wrap transitions, executing code both before and after.
1693
+ # These callbacks are defined in the exact same manner as before / after
1694
+ # callbacks with the exception that the transition must be yielded to in
1695
+ # order to finish running it.
1696
+ #
1697
+ # If defining +around+ callbacks using blocks, you must yield within the
1698
+ # transition by directly calling the block (since yielding is not allowed
1699
+ # within blocks).
1700
+ #
1701
+ # For example,
1702
+ #
1703
+ # class Vehicle
1704
+ # state_machine do
1705
+ # around_transition do |block|
1706
+ # Benchmark.measure { block.call }
1707
+ # end
1708
+ #
1709
+ # around_transition do |vehicle, block|
1710
+ # logger.info "vehicle was #{state}..."
1711
+ # block.call
1712
+ # logger.info "...and is now #{state}"
1713
+ # end
1714
+ #
1715
+ # around_transition do |vehicle, transition, block|
1716
+ # logger.info "before #{transition.event}: #{vehicle.state}"
1717
+ # block.call
1718
+ # logger.info "after #{transition.event}: #{vehicle.state}"
1719
+ # end
1720
+ # end
1721
+ # end
1722
+ #
1723
+ # Notice that referencing the block is similar to doing so within an
1724
+ # actual method definition in that it is always the last argument.
1725
+ #
1726
+ # On the other hand, if you're defining +around+ callbacks using method
1727
+ # references, you can yield like normal:
1728
+ #
1729
+ # class Vehicle
1730
+ # state_machine do
1731
+ # around_transition :benchmark
1732
+ # ...
1733
+ # end
1734
+ #
1735
+ # def benchmark
1736
+ # Benchmark.measure { yield }
1737
+ # end
1738
+ # end
1739
+ #
1740
+ # See +before_transition+ for a description of the possible configurations
1741
+ # for defining callbacks.
1742
+ def around_transition(*args, &block)
1743
+ options = (args.last.is_a?(Hash) ? args.pop : {})
1744
+ options[:do] = args if args.any?
1745
+ add_callback(:around, options, &block)
1746
+ end
1747
+
1748
+ # Creates a callback that will be invoked *after* a transition failures to
1749
+ # be performed so long as the given requirements match the transition.
1750
+ #
1751
+ # See +before_transition+ for a description of the possible configurations
1752
+ # for defining callbacks. *Note* however that you cannot define the state
1753
+ # requirements in these callbacks. You may only define event requirements.
1754
+ #
1755
+ # = The callback
1756
+ #
1757
+ # Failure callbacks get invoked whenever an event fails to execute. This
1758
+ # can happen when no transition is available, a +before+ callback halts
1759
+ # execution, or the action associated with this machine fails to succeed.
1760
+ # In any of these cases, any failure callback that matches the attempted
1761
+ # transition will be run.
1762
+ #
1763
+ # For example,
1764
+ #
1765
+ # class Vehicle
1766
+ # state_machine do
1767
+ # after_failure do |vehicle, transition|
1768
+ # logger.error "vehicle #{vehicle} failed to transition on #{transition.event}"
1769
+ # end
1770
+ #
1771
+ # after_failure :on => :ignite, :do => :log_ignition_failure
1772
+ #
1773
+ # ...
1774
+ # end
1775
+ # end
1776
+ def after_failure(*args, &block)
1777
+ options = (args.last.is_a?(Hash) ? args.pop : {})
1778
+ options[:do] = args if args.any?
1779
+ assert_valid_keys(options, :on, :do, :if, :unless)
1780
+
1781
+ add_callback(:failure, options, &block)
1782
+ end
1783
+
1784
+ # Generates a list of the possible transition sequences that can be run on
1785
+ # the given object. These paths can reveal all of the possible states and
1786
+ # events that can be encountered in the object's state machine based on the
1787
+ # object's current state.
1788
+ #
1789
+ # Configuration options:
1790
+ # * +from+ - The initial state to start all paths from. By default, this
1791
+ # is the object's current state.
1792
+ # * +to+ - The target state to end all paths on. By default, paths will
1793
+ # end when they loop back to the first transition on the path.
1794
+ # * +deep+ - Whether to allow the target state to be crossed more than once
1795
+ # in a path. By default, paths will immediately stop when the target
1796
+ # state (if specified) is reached. If this is enabled, then paths can
1797
+ # continue even after reaching the target state; they will stop when
1798
+ # reaching the target state a second time.
1799
+ #
1800
+ # *Note* that the object is never modified when the list of paths is
1801
+ # generated.
1802
+ #
1803
+ # == Examples
1804
+ #
1805
+ # class Vehicle
1806
+ # state_machine :initial => :parked do
1807
+ # event :ignite do
1808
+ # transition :parked => :idling
1809
+ # end
1810
+ #
1811
+ # event :shift_up do
1812
+ # transition :idling => :first_gear, :first_gear => :second_gear
1813
+ # end
1814
+ #
1815
+ # event :shift_down do
1816
+ # transition :second_gear => :first_gear, :first_gear => :idling
1817
+ # end
1818
+ # end
1819
+ # end
1820
+ #
1821
+ # vehicle = Vehicle.new # => #<Vehicle:0xb7c27024 @state="parked">
1822
+ # vehicle.state # => "parked"
1823
+ #
1824
+ # vehicle.state_paths
1825
+ # # => [
1826
+ # # [#<StateMachine::Transition attribute=:state event=:ignite from="parked" from_name=:parked to="idling" to_name=:idling>,
1827
+ # # #<StateMachine::Transition attribute=:state event=:shift_up from="idling" from_name=:idling to="first_gear" to_name=:first_gear>,
1828
+ # # #<StateMachine::Transition attribute=:state event=:shift_up from="first_gear" from_name=:first_gear to="second_gear" to_name=:second_gear>,
1829
+ # # #<StateMachine::Transition attribute=:state event=:shift_down from="second_gear" from_name=:second_gear to="first_gear" to_name=:first_gear>,
1830
+ # # #<StateMachine::Transition attribute=:state event=:shift_down from="first_gear" from_name=:first_gear to="idling" to_name=:idling>],
1831
+ # #
1832
+ # # [#<StateMachine::Transition attribute=:state event=:ignite from="parked" from_name=:parked to="idling" to_name=:idling>,
1833
+ # # #<StateMachine::Transition attribute=:state event=:shift_up from="idling" from_name=:idling to="first_gear" to_name=:first_gear>,
1834
+ # # #<StateMachine::Transition attribute=:state event=:shift_down from="first_gear" from_name=:first_gear to="idling" to_name=:idling>]
1835
+ # # ]
1836
+ #
1837
+ # vehicle.state_paths(:from => :parked, :to => :second_gear)
1838
+ # # => [
1839
+ # # [#<StateMachine::Transition attribute=:state event=:ignite from="parked" from_name=:parked to="idling" to_name=:idling>,
1840
+ # # #<StateMachine::Transition attribute=:state event=:shift_up from="idling" from_name=:idling to="first_gear" to_name=:first_gear>,
1841
+ # # #<StateMachine::Transition attribute=:state event=:shift_up from="first_gear" from_name=:first_gear to="second_gear" to_name=:second_gear>]
1842
+ # # ]
1843
+ #
1844
+ # In addition to getting the possible paths that can be accessed, you can
1845
+ # also get summary information about the states / events that can be
1846
+ # accessed at some point along one of the paths. For example:
1847
+ #
1848
+ # # Get the list of states that can be accessed from the current state
1849
+ # vehicle.state_paths.to_states # => [:idling, :first_gear, :second_gear]
1850
+ #
1851
+ # # Get the list of events that can be accessed from the current state
1852
+ # vehicle.state_paths.events # => [:ignite, :shift_up, :shift_down]
1853
+ def paths_for(object, requirements = {})
1854
+ PathCollection.new(object, self, requirements)
1855
+ end
1856
+
1857
+ # Marks the given object as invalid with the given message.
1858
+ #
1859
+ # By default, this is a no-op.
1860
+ def invalidate(object, attribute, message, values = [])
1861
+ end
1862
+
1863
+ # Gets a description of the errors for the given object. This is used to
1864
+ # provide more detailed information when an InvalidTransition exception is
1865
+ # raised.
1866
+ def errors_for(object)
1867
+ ''
1868
+ end
1869
+
1870
+ # Resets any errors previously added when invalidating the given object.
1871
+ #
1872
+ # By default, this is a no-op.
1873
+ def reset(object)
1874
+ end
1875
+
1876
+ # Generates the message to use when invalidating the given object after
1877
+ # failing to transition on a specific event
1878
+ def generate_message(name, values = [])
1879
+ message = (@messages[name] || self.class.default_messages[name])
1880
+
1881
+ # Check whether there are actually any values to interpolate to avoid
1882
+ # any warnings
1883
+ if message.scan(/%./).any? {|match| match != '%%'}
1884
+ message % values.map {|value| value.last}
1885
+ else
1886
+ message
1887
+ end
1888
+ end
1889
+
1890
+ # Runs a transaction, rolling back any changes if the yielded block fails.
1891
+ #
1892
+ # This is only applicable to integrations that involve databases. By
1893
+ # default, this will not run any transactions since the changes aren't
1894
+ # taking place within the context of a database.
1895
+ def within_transaction(object)
1896
+ if use_transactions
1897
+ transaction(object) { yield }
1898
+ else
1899
+ yield
1900
+ end
1901
+ end
1902
+
1903
+ # Draws a directed graph of the machine for visualizing the various events,
1904
+ # states, and their transitions.
1905
+ #
1906
+ # This requires both the Ruby graphviz gem and the graphviz library be
1907
+ # installed on the system.
1908
+ #
1909
+ # Configuration options:
1910
+ # * <tt>:name</tt> - The name of the file to write to (without the file extension).
1911
+ # Default is "#{owner_class.name}_#{name}"
1912
+ # * <tt>:path</tt> - The path to write the graph file to. Default is the
1913
+ # current directory (".").
1914
+ # * <tt>:format</tt> - The image format to generate the graph in.
1915
+ # Default is "png'.
1916
+ # * <tt>:font</tt> - The name of the font to draw state names in.
1917
+ # Default is "Arial".
1918
+ # * <tt>:orientation</tt> - The direction of the graph ("portrait" or
1919
+ # "landscape"). Default is "portrait".
1920
+ # * <tt>:human_names</tt> - Whether to use human state / event names for
1921
+ # node labels on the graph instead of the internal name. Default is false.
1922
+ def draw(graph_options = {})
1923
+ name = graph_options.delete(:name) || "#{owner_class.name}_#{self.name}"
1924
+ draw_options = {:human_name => false}
1925
+ draw_options[:human_name] = graph_options.delete(:human_names) if graph_options.include?(:human_names)
1926
+
1927
+ graph = Graph.new(name, graph_options)
1928
+
1929
+ # Add nodes / edges
1930
+ states.by_priority.each {|state| state.draw(graph, draw_options)}
1931
+ events.each {|event| event.draw(graph, draw_options)}
1932
+
1933
+ # Output result
1934
+ graph.output
1935
+ graph
1936
+ end
1937
+
1938
+ # Determines whether an action hook was defined for firing attribute-based
1939
+ # event transitions when the configured action gets called.
1940
+ def action_hook?(self_only = false)
1941
+ @action_hook_defined || !self_only && owner_class.state_machines.any? {|name, machine| machine.action == action && machine != self && machine.action_hook?(true)}
1942
+ end
1943
+
1944
+ protected
1945
+ # Runs additional initialization hooks. By default, this is a no-op.
1946
+ def after_initialize
1947
+ end
1948
+
1949
+ # Looks up other machines that have been defined in the owner class and
1950
+ # are targeting the same attribute as this machine. When accessing
1951
+ # sibling machines, they will be automatically copied for the current
1952
+ # class if they haven't been already. This ensures that any configuration
1953
+ # changes made to the sibling machines only affect this class and not any
1954
+ # base class that may have originally defined the machine.
1955
+ def sibling_machines
1956
+ owner_class.state_machines.inject([]) do |machines, (name, machine)|
1957
+ if machine.attribute == attribute && machine != self
1958
+ machines << (owner_class.state_machine(name) {})
1959
+ end
1960
+ machines
1961
+ end
1962
+ end
1963
+
1964
+ # Determines if the machine's attribute needs to be initialized. This
1965
+ # will only be true if the machine's attribute is blank.
1966
+ def initialize_state?(object)
1967
+ value = read(object, :state)
1968
+ (value.nil? || value.respond_to?(:empty?) && value.empty?) && !states[value, :value]
1969
+ end
1970
+
1971
+ # Adds helper methods for interacting with the state machine, including
1972
+ # for states, events, and transitions
1973
+ def define_helpers
1974
+ define_state_accessor
1975
+ define_state_predicate
1976
+ define_event_helpers
1977
+ define_path_helpers
1978
+ define_action_helpers if define_action_helpers?
1979
+ define_name_helpers
1980
+ end
1981
+
1982
+ # Defines the initial values for state machine attributes. Static values
1983
+ # are set prior to the original initialize method and dynamic values are
1984
+ # set *after* the initialize method in case it is dependent on it.
1985
+ def define_state_initializer
1986
+ define_helper :instance, <<-end_eval, __FILE__, __LINE__ + 1
1987
+ def initialize(*)
1988
+ self.class.state_machines.initialize_states(self) { super }
1989
+ end
1990
+ end_eval
1991
+ end
1992
+
1993
+ # Adds reader/writer methods for accessing the state attribute
1994
+ def define_state_accessor
1995
+ attribute = self.attribute
1996
+
1997
+ @helper_modules[:instance].class_eval { attr_reader attribute } unless owner_class_ancestor_has_method?(:instance, attribute)
1998
+ @helper_modules[:instance].class_eval { attr_writer attribute } unless owner_class_ancestor_has_method?(:instance, "#{attribute}=")
1999
+ end
2000
+
2001
+ # Adds predicate method to the owner class for determining the name of the
2002
+ # current state
2003
+ def define_state_predicate
2004
+ call_super = !!owner_class_ancestor_has_method?(:instance, "#{name}?")
2005
+ define_helper :instance, <<-end_eval, __FILE__, __LINE__ + 1
2006
+ def #{name}?(*args)
2007
+ args.empty? && (#{call_super} || defined?(super)) ? super : self.class.state_machine(#{name.inspect}).states.matches?(self, *args)
2008
+ end
2009
+ end_eval
2010
+ end
2011
+
2012
+ # Adds helper methods for getting information about this state machine's
2013
+ # events
2014
+ def define_event_helpers
2015
+ # Gets the events that are allowed to fire on the current object
2016
+ define_helper(:instance, attribute(:events)) do |machine, object, *args|
2017
+ machine.events.valid_for(object, *args).map {|event| event.name}
2018
+ end
2019
+
2020
+ # Gets the next possible transitions that can be run on the current
2021
+ # object
2022
+ define_helper(:instance, attribute(:transitions)) do |machine, object, *args|
2023
+ machine.events.transitions_for(object, *args)
2024
+ end
2025
+
2026
+ # Fire an arbitrary event for this machine
2027
+ define_helper(:instance, "fire_#{attribute(:event)}") do |machine, object, event, *args|
2028
+ machine.events.fetch(event).fire(object, *args)
2029
+ end
2030
+
2031
+ # Add helpers for tracking the event / transition to invoke when the
2032
+ # action is called
2033
+ if action
2034
+ event_attribute = attribute(:event)
2035
+ define_helper(:instance, event_attribute) do |machine, object|
2036
+ # Interpret non-blank events as present
2037
+ event = machine.read(object, :event, true)
2038
+ event && !(event.respond_to?(:empty?) && event.empty?) ? event.to_sym : nil
2039
+ end
2040
+
2041
+ # A roundabout way of writing the attribute is used here so that
2042
+ # integrations can hook into this modification
2043
+ define_helper(:instance, "#{event_attribute}=") do |machine, object, value|
2044
+ machine.write(object, :event, value, true)
2045
+ end
2046
+
2047
+ event_transition_attribute = attribute(:event_transition)
2048
+ define_helper :instance, <<-end_eval, __FILE__, __LINE__ + 1
2049
+ protected; attr_accessor #{event_transition_attribute.inspect}
2050
+ end_eval
2051
+ end
2052
+ end
2053
+
2054
+ # Adds helper methods for getting information about this state machine's
2055
+ # available transition paths
2056
+ def define_path_helpers
2057
+ # Gets the paths of transitions available to the current object
2058
+ define_helper(:instance, attribute(:paths)) do |machine, object, *args|
2059
+ machine.paths_for(object, *args)
2060
+ end
2061
+ end
2062
+
2063
+ # Determines whether action helpers should be defined for this machine.
2064
+ # This is only true if there is an action configured and no other machines
2065
+ # have process this same configuration already.
2066
+ def define_action_helpers?
2067
+ action && !owner_class.state_machines.any? {|name, machine| machine.action == action && machine != self}
2068
+ end
2069
+
2070
+ # Adds helper methods for automatically firing events when an action
2071
+ # is invoked
2072
+ def define_action_helpers
2073
+ if action_hook
2074
+ @action_hook_defined = true
2075
+ define_action_hook
2076
+ end
2077
+ end
2078
+
2079
+ # Hooks directly into actions by defining the same method in an included
2080
+ # module. As a result, when the action gets invoked, any state events
2081
+ # defined for the object will get run. Method visibility is preserved.
2082
+ def define_action_hook
2083
+ action_hook = self.action_hook
2084
+ action = self.action
2085
+ private_action_hook = owner_class.private_method_defined?(action_hook)
2086
+
2087
+ # Only define helper if it hasn't
2088
+ define_helper :instance, <<-end_eval, __FILE__, __LINE__ + 1
2089
+ def #{action_hook}(*)
2090
+ self.class.state_machines.transitions(self, #{action.inspect}).perform { super }
2091
+ end
2092
+
2093
+ private #{action_hook.inspect} if #{private_action_hook}
2094
+ end_eval
2095
+ end
2096
+
2097
+ # The method to hook into for triggering transitions when invoked. By
2098
+ # default, this is the action configured for the machine.
2099
+ #
2100
+ # Since the default hook technique relies on module inheritance, the
2101
+ # action must be defined in an ancestor of the owner classs in order for
2102
+ # it to be the action hook.
2103
+ def action_hook
2104
+ action && owner_class_ancestor_has_method?(:instance, action) ? action : nil
2105
+ end
2106
+
2107
+ # Determines whether there's already a helper method defined within the
2108
+ # given scope. This is true only if one of the owner's ancestors defines
2109
+ # the method and is further along in the ancestor chain than this
2110
+ # machine's helper module.
2111
+ def owner_class_ancestor_has_method?(scope, method)
2112
+ superclasses = owner_class.ancestors[1..-1].select {|ancestor| ancestor.is_a?(Class)}
2113
+
2114
+ if scope == :class
2115
+ # Use singleton classes
2116
+ current = (class << owner_class; self; end)
2117
+ superclass = superclasses.first
2118
+ else
2119
+ current = owner_class
2120
+ superclass = owner_class.superclass
2121
+ end
2122
+
2123
+ # Generate the list of modules that *only* occur in the owner class, but
2124
+ # were included *prior* to the helper modules, in addition to the
2125
+ # superclasses
2126
+ ancestors = current.ancestors - superclass.ancestors + superclasses
2127
+ ancestors = ancestors[ancestors.index(@helper_modules[scope])..-1].reverse
2128
+
2129
+ # Search for for the first ancestor that defined this method
2130
+ ancestors.detect do |ancestor|
2131
+ ancestor = (class << ancestor; self; end) if scope == :class && ancestor.is_a?(Class)
2132
+ ancestor.method_defined?(method) || ancestor.private_method_defined?(method)
2133
+ end
2134
+ end
2135
+
2136
+ # Adds helper methods for accessing naming information about states and
2137
+ # events on the owner class
2138
+ def define_name_helpers
2139
+ # Gets the humanized version of a state
2140
+ define_helper(:class, "human_#{attribute(:name)}") do |machine, klass, state|
2141
+ machine.states.fetch(state).human_name(klass)
2142
+ end
2143
+
2144
+ # Gets the humanized version of an event
2145
+ define_helper(:class, "human_#{attribute(:event_name)}") do |machine, klass, event|
2146
+ machine.events.fetch(event).human_name(klass)
2147
+ end
2148
+
2149
+ # Gets the state name for the current value
2150
+ define_helper(:instance, attribute(:name)) do |machine, object|
2151
+ machine.states.match!(object).name
2152
+ end
2153
+
2154
+ # Gets the human state name for the current value
2155
+ define_helper(:instance, "human_#{attribute(:name)}") do |machine, object|
2156
+ machine.states.match!(object).human_name(object.class)
2157
+ end
2158
+ end
2159
+
2160
+ # Defines the with/without scope helpers for this attribute. Both the
2161
+ # singular and plural versions of the attribute are defined for each
2162
+ # scope helper. A custom plural can be specified if it cannot be
2163
+ # automatically determined by either calling +pluralize+ on the attribute
2164
+ # name or adding an "s" to the end of the name.
2165
+ def define_scopes(custom_plural = nil)
2166
+ plural = custom_plural || pluralize(name)
2167
+
2168
+ [:with, :without].each do |kind|
2169
+ [name, plural].map {|s| s.to_s}.uniq.each do |suffix|
2170
+ method = "#{kind}_#{suffix}"
2171
+
2172
+ if scope = send("create_#{kind}_scope", method)
2173
+ # Converts state names to their corresponding values so that they
2174
+ # can be looked up properly
2175
+ define_helper(:class, method) do |machine, klass, *states|
2176
+ run_scope(scope, machine, klass, states)
2177
+ end
2178
+ end
2179
+ end
2180
+ end
2181
+ end
2182
+
2183
+ # Generates the results for the given scope based on one or more states to
2184
+ # filter by
2185
+ def run_scope(scope, machine, klass, states)
2186
+ values = states.flatten.map {|state| machine.states.fetch(state).value}
2187
+ scope.call(klass, values)
2188
+ end
2189
+
2190
+ # Pluralizes the given word using #pluralize (if available) or simply
2191
+ # adding an "s" to the end of the word
2192
+ def pluralize(word)
2193
+ word = word.to_s
2194
+ if word.respond_to?(:pluralize)
2195
+ word.pluralize
2196
+ else
2197
+ "#{name}s"
2198
+ end
2199
+ end
2200
+
2201
+ # Creates a scope for finding objects *with* a particular value or values
2202
+ # for the attribute.
2203
+ #
2204
+ # By default, this is a no-op.
2205
+ def create_with_scope(name)
2206
+ end
2207
+
2208
+ # Creates a scope for finding objects *without* a particular value or
2209
+ # values for the attribute.
2210
+ #
2211
+ # By default, this is a no-op.
2212
+ def create_without_scope(name)
2213
+ end
2214
+
2215
+ # Always yields
2216
+ def transaction(object)
2217
+ yield
2218
+ end
2219
+
2220
+ # Gets the initial attribute value defined by the owner class (outside of
2221
+ # the machine's definition). By default, this is always nil.
2222
+ def owner_class_attribute_default
2223
+ nil
2224
+ end
2225
+
2226
+ # Checks whether the given state matches the attribute default specified
2227
+ # by the owner class
2228
+ def owner_class_attribute_default_matches?(state)
2229
+ state.matches?(owner_class_attribute_default)
2230
+ end
2231
+
2232
+ # Updates this machine based on the configuration of other machines in the
2233
+ # owner class that share the same target attribute.
2234
+ def add_sibling_machine_configs
2235
+ # Add existing states
2236
+ sibling_machines.each do |machine|
2237
+ machine.states.each {|state| states << state unless states[state.name]}
2238
+ end
2239
+ end
2240
+
2241
+ # Adds a new transition callback of the given type.
2242
+ def add_callback(type, options, &block)
2243
+ callbacks[type == :around ? :before : type] << callback = Callback.new(type, options, &block)
2244
+ add_states(callback.known_states)
2245
+ callback
2246
+ end
2247
+
2248
+ # Tracks the given set of states in the list of all known states for
2249
+ # this machine
2250
+ def add_states(new_states)
2251
+ new_states.map do |new_state|
2252
+ # Check for other states that use a different class type for their name.
2253
+ # This typically prevents string / symbol misuse.
2254
+ if new_state && conflict = states.detect {|state| state.name && state.name.class != new_state.class}
2255
+ raise ArgumentError, "#{new_state.inspect} state defined as #{new_state.class}, #{conflict.name.inspect} defined as #{conflict.name.class}; all states must be consistent"
2256
+ end
2257
+
2258
+ unless state = states[new_state]
2259
+ states << state = State.new(self, new_state)
2260
+
2261
+ # Copy states over to sibling machines
2262
+ sibling_machines.each {|machine| machine.states << state}
2263
+ end
2264
+
2265
+ state
2266
+ end
2267
+ end
2268
+
2269
+ # Tracks the given set of events in the list of all known events for
2270
+ # this machine
2271
+ def add_events(new_events)
2272
+ new_events.map do |new_event|
2273
+ # Check for other states that use a different class type for their name.
2274
+ # This typically prevents string / symbol misuse.
2275
+ if conflict = events.detect {|event| event.name.class != new_event.class}
2276
+ raise ArgumentError, "#{new_event.inspect} event defined as #{new_event.class}, #{conflict.name.inspect} defined as #{conflict.name.class}; all events must be consistent"
2277
+ end
2278
+
2279
+ unless event = events[new_event]
2280
+ events << event = Event.new(self, new_event)
2281
+ end
2282
+
2283
+ event
2284
+ end
2285
+ end
2286
+ end
2287
+ end