README.markdown in micromachine-0.0.9 vs README.markdown in micromachine-0.0.10
- old
+ new
@@ -34,10 +34,19 @@
machine.on(:confirmed) do
puts "Confirmed"
end
+Or callbacks on any transition:
+
+ machine.on(:any) do
+ puts "Transitioned..."
+ end
+
+Note that `:any` is a special key. Using it as a state when declaring
+transitions will give you unexpected results.
+
Adding MicroMachine to your models
----------------------------------
The most popular pattern among Ruby libraries that tackle this problem
is to extend the model and transform it into a finite state machine.
@@ -79,9 +88,38 @@
end
This example asumes you have a :confirmation_state attribute in your
model. This may look like a very verbose implementation, but you gain a
lot in flexibility.
+
+An alternative approach, using callbacks:
+
+ class Event < ActiveRecord::Base
+ def confirm!
+ confirmation.trigger(:confirm)
+ end
+
+ def cancel!
+ confirmation.trigger(:cancel)
+ end
+
+ def reset!
+ confirmation.trigger(:reset)
+ end
+
+ def confirmation
+ @confirmation ||= begin
+ confirmation = MicroMachine.new(confirmation_state || "pending")
+ confirmation.transitions_for[:confirm] = { "pending" => "confirmed" }
+ confirmation.transitions_for[:cancel] = { "confirmed" => "cancelled" }
+ confirmation.transitions_for[:reset] = { "confirmed" => "pending", "cancelled" => "pending" }
+ confirmation.on(:any) { self.confirmation_state = confirmation.state }
+ confirmation
+ end
+ end
+ end
+
+Now, on any transition the `confirmation_state` attribute in the model will be updated.
Installation
------------
$ sudo gem install micromachine