Integrate MicroMachine with models via composition
masterMicroMachine is designed for composition rather than being a mixin. To use it within a model (like ActiveRecord), instantiate the machine inside a method and manage the persistence of the state yourself.
Two common patterns:
- Manual Persistence: Use a lifecycle hook (like
before_save) to copy the machine's current state to a database column. - Callback-based Persistence: Use
machine.on(:any)to update the model's attribute automatically whenever a transition occurs.
class Event < ActiveRecord::Base
def confirmation
@confirmation ||= begin
# Initialize machine with current persisted state
fsm = MicroMachine.new(confirmation_state || "pending")
fsm.when(:confirm, "pending" => "confirmed")
fsm.when(:cancel, "confirmed" => "cancelled")
fsm.when(:reset, "confirmed" => "pending", "cancelled" => "pending")
# Option: Automatically sync state to the model on any transition
fsm.on(:any) { self.confirmation_state = fsm.state }
fsm
end
end
def confirm!
confirmation.trigger(:confirm)
end
end