Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created September 26, 2019 11:54
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 havenwood/047371c804c9aedc733f59c077a1e86a to your computer and use it in GitHub Desktop.
Save havenwood/047371c804c9aedc733f59c077a1e86a to your computer and use it in GitHub Desktop.
Response to nima_m on #ruby IRC asking how to implement this state machine in Ruby: https://pasteboard.co/Izbzhuz.png
# frozen_string_literal: true
class Heater
STATE = {
s1: {heater: false, cooler: false},
s2: {heater: false, cooler: true},
s3: {heater: true, cooler: false}
}.freeze
attr_reader :state
attr_reader :cooler
attr_reader :heater
def initialize(state: :s1)
@state = state
start
end
def start
Thread.abort_on_exception = true
@thread = Thread.new do
loop do
STATE.fetch(@state).each do |key, value|
instance_variable_set "@#{key}", value
end
event = wait_for_event
new_state = public_send @state, event
@state = new_state if new_state
end
end
end
def s1(event)
case event
when 'T<15'
:s3
when 'T>35'
:s2
end
end
def s2(event)
:s1 if event == 'T<25'
end
def s3(_event)
:s1 if event == 'T>30'
end
def wait_for_event
sleep Math::E
%w[T<15 T<25 T>30 T>35].sample
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment