MongoMapper state machine? just use active model's state machine

MongoMapper

Active Model State Machine

So you want a state machine for you mongo mapper? Active model now comes with a nice looking state machine;
I really like the multi parameters you can send to the on_transition methods;

  class StateMachineSubject
    state_machine :chetan_patil, :initial => :sleeping do
      state :sleeping
      state :showering
      state :working
      state :dating

      event :wakeup do
        transitions :from => :sleeping, :to => [:showering, :working]
      end

      event :dress do
        transitions :from => :sleeping, :to => :working, :on_transition => :wear_clothes
      end
    end

    def wear_clothes(shirt_color, trouser_type)
      # do whatever
    end
  end

  # Check this out!
  @instance.dress!(:chetan_patil, 'purple', 'dressy')

So you just need to include ActiveModel::StateMachine into your model and away you go

But I am sure you would like your states to be persisted; well to add persistence
just add what the api is looking for; read_state and write_state methods; Done;

  key :model_state, String

  # @param [ActiveModel::StateMachine::Machine] sm
  # @param [Symbol] state
  def write_state(sm, state)
    update_attributes!(:model_state => state.to_s)
  end

  # @return [Symbol]
  def read_state(sm)
    self.model_state.to_sym
  end

Update

State machine has just been taken out of active model; probably for the Beta Release of Rails3 as it is lacking some docs;
I am sure it will be back; but for now one has to go back in time to get what they need;

2 Comments

RSS feed for comments on this post. TrackBack URL

  1. Ben Mabey — June 7, 2010

    FYI, someone extracted this out into a gem that can be used before it is added back for 3.0.

  2. Yasuko Trent — February 6, 2011

    I admire your work , thanks for all the interesting posts .

Leave a comment

Preview: