State Machine Simulator
April 1st, 2008
If you need to create a wizard, with forward and back buttons for several different steps, a great way to do it is to use the acts_as_state_machine plugin.
But for just two or three steps, loading a whole plugin seems like overkill. Instead of loading a whole plugin, you can simulate the same functionality by dropping next!
and previous!
methods into your model like so:
# State Machine
# Guilt-free stateful modeling!
# These two simple methods simulate all the goodness of
# acts_as_state_machine without the added fat of an included plugin.
def next!
next_step = case self.state
when "step1"
"step2"
when "step2"
"step3"
when "step3"
"step3"
end
self.update_attribute(:state, next_step)
end
def previous!
previous_step = case self.state
when "step1"
"step1"
when "step2"
"step1"
when "step3"
"step2"
end
self.update_attribute(:state, previous_step)
end
def current_step
@current_step ||= self.state
end
1 Response to “State Machine Simulator”
Sorry, comments are closed for this article.
April 29th, 2008 at 03:38 PM