Skip to content

Instantly share code, notes, and snippets.

@cheeyeo
Created May 12, 2014 20:30
Show Gist options
  • Save cheeyeo/b4864920aa1711cdacbe to your computer and use it in GitHub Desktop.
Save cheeyeo/b4864920aa1711cdacbe to your computer and use it in GitHub Desktop.
Example of using classes to represent states, removing the need for case statements
class TrafficLight
class State
def to_s
name
end
def name
self.class.name.split('::').last.downcase
end
def signal(traffic_light)
traffic_light.turn_on_lamp(color.to_sym)
end
end
class Stop < State
def color; 'red'; end
def next_state; Proceed.new; end
end
class Caution < State
def color; 'yellow'; end
def next_state; Stop.new; end
def signal(traffic_light)
super
traffic_light.ring_warning_bell
end
end
class Proceed < State
def color; 'green'; end
def next_state; Caution.new; end
end
def change_to(state)
@state = State(state)
end
def signal
@state.signal(self)
end
def next_state
@state.next_state
end
def turn_on_lamp(color)
puts "Turning on #{color}"
end
def ring_warning_bell
puts "Ring ring ring!"
end
private
def State(state)
case state
when State then
state
else
self.class.const_get(state.to_s.capitalize).new
end
end
end
light = TrafficLight.new
light.change_to(:caution)
light.signal
puts "Next state is #{light.next_state}"
light.change_to(:stop)
light.signal
puts "Next state is #{light.next_state}"
light.change_to(:proceed)
light.signal
puts "Next state is #{light.next_state}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment