zilkey (owner)

Revisions

gist: 153885 Download_button fork
public
Description:
Data-backed state machine example
Public Clone URL: git://gist.github.com/153885.git
Embed All Files: show embed
data centric state machine.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
# The following is an example of how to model a finite state machine using ruby objects.
# It supports:
# - determining if a crud action can be taken (can_read?, can_update? etc...) in a given state, with conditions
# - blocking illegal state changes, with conditions
# - executing entry and exit events for states, with conditions
# - relying entirely on objects that can be persisted in a database - that is, no DSL or ruby code necessary beyond including the module
# - storing a history of state transitions
# - being able to safely store method names that will be called on an object, using a mapping so that you can control the methods that are executed
# - is only about 70 lines of code, and could be shortened
#
# While it doesn't support it yet, it would be relatively easy to add support for adding a pluck-like way of defining conditions on actions, like :conditions => [{:user => :admin?}, :paid?]
# Just change ActiveHash::Base to ActiveRecord::Base, write a few migrations and you could easily manage state machine meta data in a database
 
require 'rubygems'
require 'spec'
require 'active_hash'
 
class IllegalStateTransition < StandardError
end
 
class Action < ActiveHash::Base
  fields :name, :target
  field :conditions, :default => []
end
 
# this concept might be useful at some point to organize admin screens
class Machine < ActiveHash::Base
  fields :states, :initial
end
 
class State < ActiveHash::Base
  field :name
  field :input_actions, :default => []
  field :transition_actions, :default => []
  field :entry_actions, :default => []
  field :exit_actions, :default => []
 
  def actions_hash
    {
      :input => input_actions,
      :transition => transition_actions,
      :entry => entry_actions,
      :exit => exit_actions
    }
  end
 
end
 
class StateTransition < ActiveHash::Base
  fields :from, :to, :by, :on, :message
end
 
class User < ActiveHash::Base
  fields :admin?, :account_admin?
end
 
module HasState
 
  def state_transitions
    @state_transitions ||= []
  end
 
  def can_update?
    can_perform_action?(:update)
  end
 
  def can_delete?
    can_perform_action?(:delete)
  end
 
  def can_view?
    can_perform_action?(:view)
  end
 
  def can_perform_action?(action)
    available_input_actions.map(&:name).include?(action)
  end
 
  def available_transitions
    available_actions(state, :transition)
  end
 
  def available_new_state_names
    available_actions(state, :transition).map(&:target)
  end
 
  def available_input_actions
    available_actions(state, :input)
  end
 
  def state=(new_state)
    if new_state.present? && state?
      raise IllegalStateTransition unless available_new_state_names.include?(new_state.name)
      execute_callbacks_for(state, :exit)
      execute_callbacks_for(new_state, :entry)
    end
    state_transitions << StateTransition.new(:from => state, :to => new_state, :on => Time.now)
    attributes[:state] = new_state
  end
 
  def available_actions(state, type)
    [].tap do |results|
      if state
        state.actions_hash[type].each do |action|
          conditions = action.conditions.map{|condition| send_action_method(condition) }
          if conditions.empty? || (conditions.present? && conditions.all?{|condition| condition == true})
            results << action
          end
        end
      end
    end
  end
 
  def execute_callbacks_for(state, action_name)
    available_actions(state, action_name).each{ |action| send_action_method(action.name) }
  end
 
 
  def send_action_method(method)
    send action_method_mapping[method]
  end
 
  def action_method_mapping
    {}
  end
 
end
 
class Invoice < ActiveHash::Base
  fields :user, :state, :paid
  attr_reader :emails, :number
  include HasState
 
  def deliver_emails
    @emails = [:email1, :email2]
  end
 
  def assign_number
    @number = 1234
  end
 
  # You could expose this list to an admin UI
  def action_method_mapping
    {
      :send_emails => :deliver_emails,
      :paid? => :paid?,
      :assign_number => :assign_number
    }
  end
end
 
describe Invoice do
 
  describe "#state=" do
 
    context "to a nil state" do
      it "sets state to nil" do
        draft = State.new :id => 1, :name => :draft
        invoice = Invoice.new :state => draft
        invoice.state.should == draft
        invoice.state = nil
        invoice.state.should be_nil
      end
 
      it "records a state transition" do
        draft = State.new :id => 1, :name => :draft
        invoice = Invoice.new :state => draft
        invoice.state_transitions.should be_empty
        invoice.state = nil
        invoice.state_transitions.length.should == 1
      end
    end
 
    context "from a nil state" do
      it "sets state to nil" do
        draft = State.new :id => 1, :name => :draft
        invoice = Invoice.new
        invoice.state.should be_nil
        invoice.state = draft
        invoice.state.should == draft
      end
    end
 
    context "from a state that has a transition that includes the new state" do
      before do
        @draft = State.new :id => 1, :name => :draft, :transition_actions => [
          Action.new(:name => :post, :target => :posted)
        ]
        @posted = State.new :id => 2, :name => :posted
      end
 
      it "allows the state transition to happen" do
        invoice = Invoice.new :state => @draft
        invoice.state.should == @draft
        invoice.state = @posted
        invoice.state.should == @posted
      end
    end
 
    context "from a state for which there are no transitions that match the new state" do
      before do
        @draft = State.new :id => 1, :name => :draft, :transition_actions => [
          Action.new(:name => :fry, :target => :fried)
        ]
        @posted = State.new :id => 2, :name => :posted
      end
 
      it "allows the state transition to happen" do
        invoice = Invoice.new :state => @draft
        invoice.state.should == @draft
        proc do
          invoice.state = @posted
        end.should raise_error(IllegalStateTransition)
      end
    end
 
    context "from a state for which there is a transition with conditions" do
      before do
        @draft = State.new :id => 1, :name => :draft, :transition_actions => [
          Action.new(:name => :post, :target => :posted, :conditions => [:paid?])
        ]
        @posted = State.new :id => 2, :name => :posted
      end
 
      context "and the object meets the criteria" do
        it "allows the transition to happen" do
          invoice = Invoice.new :state => @draft, :paid => true
          invoice.state.should == @draft
          invoice.state = @posted
          invoice.state.should == @posted
        end
      end
 
      context "and the object does not meet the criteria" do
        it "does not allow the transition to happen" do
          invoice = Invoice.new :state => @draft, :paid => false
          invoice.state.should == @draft
          proc do
            invoice.state = @posted
          end.should raise_error(IllegalStateTransition)
        end
      end
    end
 
    describe "new state entry events" do
      context "when the new state is nil" do
        it "does nothing" do
          proc do
            invoice = Invoice.new
            invoice.state = nil
          end.should_not raise_error
        end
      end
 
      context "when the new state has entry events with no conditions" do
        before do
          @draft = State.new :name => :draft, :transition_actions => [
            Action.new(:name => :post, :target => :posted)
          ]
          @posted = State.new :name => :posted,
                              :entry_actions => [
                                Action.new(:name => :send_emails),
                                Action.new(:name => :assign_number)
                              ]
        end
 
        it "fires each of the entry events" do
          invoice = Invoice.new :state => @draft
          invoice.emails.should be_nil
          invoice.number.should be_nil
          invoice.state = @posted
          invoice.emails.should_not be_nil
          invoice.number.should_not be_nil
        end
      end
 
      context "when the new state has entry events with conditions" do
        context "and the object meets the conditions" do
          before do
            @draft = State.new :name => :draft, :transition_actions => [
              Action.new(:name => :post, :target => :posted)
            ]
            @posted = State.new :name => :posted,
                                :entry_actions => [
                                  Action.new(:name => :send_emails, :conditions => [:paid?])
                                ]
          end
 
          it "fires each of the entry events" do
            invoice = Invoice.new :state => @draft, :paid => true
            invoice.emails.should be_nil
            invoice.state = @posted
            invoice.emails.should_not be_nil
          end
        end
 
        context "and the object does not meet the conditions" do
          before do
            @draft = State.new :name => :draft, :transition_actions => [
              Action.new(:name => :post, :target => :posted)
            ]
            @posted = State.new :name => :posted,
                                :entry_actions => [
                                  Action.new(:name => :send_emails, :conditions => [:paid?]),
                                  Action.new(:name => :assign_number)
                                ]
          end
 
          it "fires each of the entry events for which it passes the conditions" do
            invoice = Invoice.new :state => @draft, :paid => false
            invoice.emails.should be_nil
            invoice.number.should be_nil
            invoice.state = @posted
 
            invoice.emails.should be_nil
            invoice.number.should_not be_nil
          end
 
        end
      end
    end
 
    describe "old state exit actions" do
      context "when the old state has exit actions with no conditions" do
        before do
          @draft = State.new :name => :draft,
                              :transition_actions => [
                                Action.new(:name => :post, :target => :posted)
                              ],
                              :exit_actions => [
                                Action.new(:name => :send_emails),
                                Action.new(:name => :assign_number)
                              ]
          @posted = State.new :name => :posted
 
        end
 
        it "fires each of the exit actions" do
          invoice = Invoice.new :state => @draft
          invoice.emails.should be_nil
          invoice.number.should be_nil
          invoice.state = @posted
          invoice.emails.should_not be_nil
          invoice.number.should_not be_nil
        end
      end
 
      context "when the old state has exit actions with conditions" do
        context "and the object meets the conditions" do
          before do
            @draft = State.new :name => :draft,
                                :transition_actions => [
                                  Action.new(:name => :post, :target => :posted)
                                ],
                                :exit_actions => [
                                  Action.new(:name => :send_emails, :conditions => [:paid?])
                                ]
            @posted = State.new :name => :posted
          end
 
          it "fires each of the exit actions" do
            invoice = Invoice.new :state => @draft, :paid => true
            invoice.emails.should be_nil
            invoice.state = @posted
            invoice.emails.should_not be_nil
          end
        end
 
        context "and the object does not meet the conditions" do
          before do
            @draft = State.new :name => :draft,
                                :transition_actions => [
                                  Action.new(:name => :post, :target => :posted)
                                ],
                                :exit_actions => [
                                  Action.new(:name => :send_emails, :conditions => [:paid?]),
                                  Action.new(:name => :assign_number)
                                ]
            @posted = State.new :name => :posted
          end
 
          it "fires each of the exit actions for which it passes the conditions" do
            invoice = Invoice.new :state => @draft, :paid => false
            invoice.emails.should be_nil
            invoice.number.should be_nil
            invoice.state = @posted
 
            invoice.emails.should be_nil
            invoice.number.should_not be_nil
          end
 
        end
      end
    end
 
  end
 
  describe "#available_transitions" do
    context "when there is an object without a state" do
      it "returns an empty array" do
        Invoice.new.available_transitions.should be_empty
      end
    end
 
    context "when there is a state with no transition actions" do
      before do
        @draft = State.new :name => :draft
      end
 
      it "returns an empty array" do
        invoice = Invoice.new :state => @draft
        invoice.available_transitions.should be_empty
      end
    end
 
    context "when there is a state with transition actions" do
      before do
        @draft = State.new :name => :draft,
                           :transition_actions => [
                             Action.new(:id => 1, :name => :post, :target => :posted)
                           ]
      end
 
      it "returns the array of transition actions" do
        invoice = Invoice.new :state => @draft
        invoice.available_transitions.should == [Action.new(:id => 1)]
      end
    end
 
    context "when there is a state with transition actions with conditions" do
      before do
        @draft = State.new :name => :draft,
                           :transition_actions => [
                             Action.new(:id => 1, :name => :post, :target => :posted, :conditions => [:paid?]),
                             Action.new(:id => 2, :name => :post, :target => :posted)
                           ]
      end
 
      context "and the object meets those conditions" do
        it "returns the array of transition actions" do
          invoice = Invoice.new :state => @draft, :paid => true
          invoice.available_transitions.should include( Action.new(:id => 1) )
        end
      end
 
      context "and the object does not meet those conditions" do
        it "does not include the transitions for which the conditions are not met" do
          invoice = Invoice.new :state => @draft, :paid => false
          invoice.available_transitions.should_not include( Action.new(:id => 1) )
        end
      end
    end
  end
 
  describe "available_input_actions" do
    context "when there is an object without a state" do
      it "returns an empty array" do
        Invoice.new.available_input_actions.should be_empty
      end
    end
 
    context "when there is a state with no input actions" do
      before do
        @draft = State.new :name => :draft
      end
 
      it "returns an empty array" do
        invoice = Invoice.new :state => @draft
        invoice.available_input_actions.should be_empty
      end
    end
 
    context "when there are input actions :update" do
      before do
        @draft = State.new :name => :draft,
                           :input_actions => [
                             Action.new(:id => 1, :name => :update),
                             Action.new(:id => 2, :name => :delete)
                           ]
      end
 
      it "returns the input actions" do
        invoice = Invoice.new :state => @draft
        invoice.available_input_actions.should include( Action.new(:id => 1) )
        invoice.available_input_actions.should include( Action.new(:id => 2) )
        invoice.can_update?.should be_true
        invoice.can_delete?.should be_true
        invoice.can_view?.should be_false
      end
    end
 
    context "when there is a state with input actions with conditions" do
      before do
        @draft = State.new :name => :draft,
                           :input_actions => [
                             Action.new(:id => 1, :name => :update, :conditions => [:paid?])
                           ]
      end
 
      context "and the object meets those conditions" do
        it "returns the array of input actions" do
          invoice = Invoice.new :state => @draft, :paid => true
          invoice.available_input_actions.should include( Action.new(:id => 1) )
        end
      end
 
      context "and the object does not meet those conditions" do
        it "does not include the transitions for which the conditions are not met" do
          invoice = Invoice.new :state => @draft, :paid => false
          invoice.available_input_actions.should_not include( Action.new(:id => 1) )
        end
      end
    end
  end
end