Skip to content

Instantly share code, notes, and snippets.

@jasoncale
Created June 5, 2009 08:19
Show Gist options
  • Save jasoncale/124148 to your computer and use it in GitHub Desktop.
Save jasoncale/124148 to your computer and use it in GitHub Desktop.
# State machine
# ensure default state is set.
def before_create
ensure_default_state
end
def ensure_default_state
(self.state = Brief.default_state) if read_attribute(:state).blank?
end
# define states and associated actions
state :draft, :default => true do
handle :publish! do
transition_to :published
save!
end
end
state :published do
handle :close! do
transition_to :closed
save!
end
handle :review! do
transition_to :peer_review
save!
end
end
state :peer_review do
handle :close! do
transition_to :closed
save!
end
end
state :closed
# overwrite accessors so we can save to the database
def state=(transition_to)
write_attribute(:state, transition_to.to_s)
end
def state
ensure_default_state
read_attribute(:state)
end
# dynamically create some class level, and instance methods
# for use with the statemachine defined states.
class_eval do
states.each do |state_name, state|
# create a named scope for all the defined scopes
named_scope state_name, :conditions => ["state = ?", state_name.to_s]
# create a state_name? instance method for each state ..
# for example @brief.draft? => true
define_method("#{state_name}?", lambda { self.state == state_name })
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment