Skip to content

Instantly share code, notes, and snippets.

@mmm
Created February 24, 2012 20:16
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 mmm/1903456 to your computer and use it in GitHub Desktop.
Save mmm/1903456 to your computer and use it in GitHub Desktop.
poor man's state machine
#
# move the following into lib/state_machine.rb or something?
# Also, the state transitions are not really atomic...
# works fine for now, but should fix eventually
#
%w(
new
validating
valid
invalid
ready
running
finished
failed
stopped
).each do |status_entry|
class_eval <<-EOS
def in_state_#{status_entry}?
self.status == "#{status_entry}"
end
def set_state_#{status_entry}(should_save = true)
self.status_updated_at = Time.now
self.status = "#{status_entry}"
if should_save
self.update_attribute(:status, status)
end
end
EOS
instance_eval <<-EOS
named_scope :in_state_#{status_entry}, :conditions => [ 'status = ?', "#{status_entry}" ]
EOS
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment