Skip to content

Instantly share code, notes, and snippets.

@cmdrkeene
Created December 14, 2009 22:43
Show Gist options
  • Save cmdrkeene/256508 to your computer and use it in GitHub Desktop.
Save cmdrkeene/256508 to your computer and use it in GitHub Desktop.

State Machines in Ruby

Acts as State Machine (AASM)

gem install rubyist-aasm

Example

include AASM

aasm_initial_state :pending

aasm_state :pending
aasm_state :assigned
aasm_state :archived
aasm_state :ignored

aasm_event :assign do
  transitions :from => :pending, :to => :assigned
end

aasm_event :ignore do
  transitions :from => :pending, :to => :ignored, :guard => lambda { |mention| !mention.sentiment? }
end

aasm_event :archive do
  transitions :from => :pending, :to => :archived
  transitions :from => :assigned, :to => :archived
end

aasm_event :restore do
  transitions :from => :archived, :to => :pending
  transitions :from => :ignored, :to => :pending
end

State Machine

gem install state_machine

Example

state_machine :state, :initial => :pending do
  event :assign do
    transition :pending => :assigned
  end

  event :ignore do
    transition :pending => :ignored, :if => :sentiment?
  end

  event :archive do
    transition [:pending, :assigned] => :archived
  end

  event :restore do
    transition [:archived, :ignored] => :pending
  end
end

Differences

Named Scopes

AASM gives you scopes for free (e.g. with a state :pending, you get a scope called 'pending')

State Machine doesn't do this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment