Last active
December 27, 2015 12:59
-
-
Save Fosome/7329822 to your computer and use it in GitHub Desktop.
Rubs refactoring
This file contains hidden or 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 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