Skip to content

Instantly share code, notes, and snippets.

@alexdesi
Created October 8, 2019 09:13
Show Gist options
  • Save alexdesi/2c9a8bbe3fe6d5f67311c1a35d324a66 to your computer and use it in GitHub Desktop.
Save alexdesi/2c9a8bbe3fe6d5f67311c1a35d324a66 to your computer and use it in GitHub Desktop.
Mini state machine
# THIS IS WIP, NOT FULLY WORKING
class MiniStateMachine
# [initial_statuses, event, next_status]
@transitions = [
[[:s1, :s2], :event1, :s3],
[[:s3], :event2, :s4],
[[:s1, :s2], :event3, :s5]
]
def initialize(state)
raise 'State do not exist' unless all_statuses.include? state
@current_state = state
end
def apply_event!(event)
transition = @transitions
.find { |statuses, event_for_statuses, final_state|
statuses.include? current_state && event_for_statuses == event
}
new_state = transition[2]
new_state
end
private
def all_statuses
@transitions
.map { |transition| transition.first }
.flatten
.uniq
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment