Created
February 1, 2013 10:12
-
-
Save andreapavoni/4690486 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module SimpleStateMachine | |
extend ActiveSupport::Concern | |
# instance methods | |
included do | |
def current_step | |
# model that includes this module must have a field called 'current_step' | |
super || steps.first | |
end | |
def next_step | |
(self.current_step = steps[steps.index(current_step)+1]) unless last_step? | |
end | |
def previous_step | |
(self.current_step = steps[steps.index(current_step)-1]) unless first_step? | |
end | |
def first_step? | |
current_step == steps.first | |
end | |
def last_step? | |
current_step == steps.last | |
end | |
end # instance methods | |
module ClassMethods | |
# Define a simple linear state machine. | |
# | |
# steps - Array of Strings representing steps (order matters). | |
# | |
# Examples | |
# | |
# has_linear_steps %w[step1 step2 stepN] | |
# | |
# Returns self | |
def has_linear_steps(steps) | |
define_method :steps do | |
steps | |
end | |
end | |
end # class methods | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment