Skip to content

Instantly share code, notes, and snippets.

@localredhead
Last active December 14, 2015 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save localredhead/5115053 to your computer and use it in GitHub Desktop.
Save localredhead/5115053 to your computer and use it in GitHub Desktop.
State machine setup.
class SomeClass < ActiveRecord::Base
STATES = {:is_valid => 0, :needs_review => 1, :reviewed => 2, :is_invalid => 3}
def initialize(*args)
super(*args)
end
attr_accessible :state
state_machine :state, :initial => STATES.key(0) do
STATES.each do |key, value|
state key, :value => value
end
event "set_#{STATES.key(0).to_s}".to_sym do
transition all => STATES.key(0)
end
event "set_#{STATES.key(1).to_s}".to_sym do
transition all => STATES.key(1)
end
event "set_#{STATES.key(2).to_s}".to_sym do
transition all => STATES.key(2)
end
event "set_#{STATES.key(3).to_s}".to_sym do
transition all => STATES.key(3)
end
state STATES.key(0) do
#placeholder
end
state STATES.key(1) do
#placeholder
end
state STATES.key(2) do
#placeholder
end
state STATES.key(3) do
#placeholder
end
after_transition :on => "set_#{STATES.key(3).to_s}".to_sym, :do => :mark_deleted #super method
end
def mark_valid
self.fire_state_event("set_#{STATES.key(0).to_s}".to_sym)
end
def mark_invalid
self.fire_state_event("set_#{STATES.key(3).to_s}".to_sym)
end
def mark_needs_review
self.fire_state_event("set_#{STATES.key(1).to_s}".to_sym)
end
def mark_reviewed
self.fire_state_event("set_#{STATES.key(2).to_s}".to_sym)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment