Skip to content

Instantly share code, notes, and snippets.

@Fosome
Last active December 27, 2015 12:59
Show Gist options
  • Select an option

  • Save Fosome/7329822 to your computer and use it in GitHub Desktop.

Select an option

Save Fosome/7329822 to your computer and use it in GitHub Desktop.
Rubs refactoring
class TrafficLight
def initialize
@state = lights.first
end
def change_to(change)
light = lights.find{|l| l.color == change.to_sym }
raise ArgumentError, "Invalid traffic light: #{change}" unless light
@state = light
end
def signal
@state.signal
end
def next_state
@state.next
end
private
def lights
@lights ||= [
Proceed.new,
Caution.new,
Stop.new
]
end
class Light
NEXT = {
:green => 'caution',
:yellow => 'stop',
:red => 'proceed'
}
attr_reader :color
def initialize
raise NotImplementedError
end
def signal
puts "Turning on #{color} lamp"
end
def next
NEXT[color]
end
end
class Proceed < Light
def initialize
@color = :green
end
end
class Caution < Light
def initialize
@color = :yellow
end
def signal
super
puts "Ring ring ring!"
end
end
class Stop < Light
def initialize
@color = :red
end
end
end
t = TrafficLight.new
[
:yellow,
:red,
:green
].each do |state|
t.signal
t.next_state
t.change_to(state)
end
t.change_to(:green)
t.change_to("yellow")
t.change_to("purple")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment