Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

About this user

Jamie Wilkinson http://tramchase.com

« Newer Snippets
Older Snippets »
1 total  XML / RSS feed 

acts_as_state_machine model

// ActiveRecord plugin for managing state changes
// elitists.textdriven.com/svn/plugins/acts_as_state_machine/

class Something < ActiveRecord::Base

  # Validations
  validate :validate_state_change

  # State Machine States
  acts_as_state_machine :initial => :new
  state :new
  state :enabled,   :after => :after_enabled
  state :disabled,  :after => :after_disabled

  # State Machine Events
  event :enabled do
    transitions :from => :new,      :to => :enabled
    transitions :from => :disabled, :to => :enabled
  end
  
  event :disabled do
    transitions :from => :new,      :to => :disabled
    transitions :from => :enabled,  :to => :disabled
  end

  # Instance Methods
  def validate_state_change
    return if new_record?
    old = self.class.find(id)
    old_state = old.state
    new_state = self.state
    self.state = old_state
    if old_state != new_state
      begin
        if self.method("#{new_state}!").call != true
          errors.add(:state, "cannot transition from #{old_state} to #{new_state}")
        end
      rescue NameError
      end
      self.state = new_state
    end
  end
end
« Newer Snippets
Older Snippets »
1 total  XML / RSS feed