public
Created

  • Download Gist
state_machine.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.