Last active
August 29, 2015 14:11
-
-
Save jcasimir/97449876e82fd75033e3 to your computer and use it in GitHub Desktop.
Oven
This file contains 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
class Oven | |
attr_reader :state | |
def initialize | |
@state = InactiveState.new | |
end | |
def temp_up | |
@state = state.temp_up | |
end | |
def bake | |
@state = state.bake | |
end | |
end | |
class InactiveState | |
def temp_up | |
self | |
end | |
def bake | |
SetTemperatureState300.new | |
end | |
end | |
temps = (300...500).select{|t| t % 5 == 0} | |
temps.each do |temp| | |
class_name = "SetTemperatureState#{temp}" | |
Object.const_set(class_name, | |
Class.new do | |
def current_temp | |
self.class.to_s[-3..-1].to_i | |
end | |
def temp_up | |
next_state = "SetTemperatureState#{current_temp + 5}" | |
next_class = Object.const_get(next_state) | |
return next_class.new | |
end | |
end | |
) | |
end | |
class SetTemperatureState500 | |
def temp_up | |
self | |
end | |
end |
This file contains 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
require 'minitest/autorun' | |
require './oven' | |
class OvenTest < Minitest::Test | |
def test_it_starts_inactive | |
oven = Oven.new | |
assert oven.state.kind_of?(InactiveState) | |
end | |
def test_temp_up_is_inert_when_inactive | |
oven = Oven.new | |
oven.temp_up | |
assert oven.state.kind_of?(InactiveState) | |
end | |
def test_bake_activates_temp_setter_when_inactive | |
oven = Oven.new | |
oven.bake | |
assert oven.state.kind_of?(SetTemperatureState300) | |
end | |
end | |
class SetTemperatureStateTest < Minitest::Test | |
def test_temp_up_increases_temperature | |
state = SetTemperatureState300.new | |
state = state.temp_up | |
assert state.kind_of?(SetTemperatureState305) | |
state = state.temp_up | |
assert state.kind_of?(SetTemperatureState310) | |
end | |
def test_temp_maxes_out_at_500 | |
state = SetTemperatureState300.new | |
50.times{ state = state.temp_up } | |
assert state.kind_of?(SetTemperatureState500) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment