Rails State Machine
I think it’s crazy when I implement something that “Surely, I’m the only one that’ll ever use this”, and then another implementation ends up in Rails proper. Last year, I wrote acts_as_fsm; a state machine implementation for ActiveRecord models:
SaleMachine = Fsm::state_machine do state :new => :queued state :queued => :new state :queued => :on_site do |sale, old, new| sale.started_at = Time.now end state :on_site => :processing_orders do |sale, old, new| sale.ended_at = Time.now sale.orders.each do |o| o.status_items << OrderStatusItem.new(:status => "CLOSE_WAIT", :message => "Sale ended. Waiting for a few stragglers" ); o.save! end end state :processing_orders => :shipped endAnd then, to use the machine:
class Sale < ActiveRecord::Base acts_as_fsm :machine => SaleMachine endThere is nothing I love more than throwing away code I wrote and migrating to something in the framework. Less stuff for me to maintain. Check out ActiveRecord::StateMachine.