Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
72 lines (56 sloc) 1.23 KB
require_relative "pillar"
class PillarCircle
class NormalState
def process_pillars(pillars)
pillars.all?(&:active?) ? FinalState.new : self
end
def to_sym
:normal
end
end
class FinalState
def process_pillars(pillars)
pillars.all?(&:dormant?) ? NormalState.new : self
end
def to_sym
:final
end
end
PILLAR_COUNT = 10
attr_reader :state
def initialize
@state = NormalState.new
@pillars = PILLAR_COUNT.times.map { |i| Pillar.new(self, i) }
@listeners = []
end
def add_listener(callable = nil, &block)
callable ||= block
@listeners << callable
@pillars.each { |pillar| pillar.add_listener(callable) }
end
def pillar(index)
@pillars.fetch(index)
end
def process_sensor_on(index)
pillar(index).process_sensor_on
update_state
end
def process_sensor_off(index)
pillar(index).process_sensor_off
update_state
end
def normal?
state.is_a? NormalState
end
def final?
state.is_a? FinalState
end
private
def update_state
prev_state = state
@state = prev_state.process_pillars(@pillars)
if @state != prev_state
@listeners.each { |listener| listener.call(self, @state.to_sym) }
end
end
end
You can’t perform that action at this time.