Created
January 19, 2012 03:45
-
-
Save banister/1637648 to your computer and use it in GitHub Desktop.
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 Match | |
attr_accessor :matcher, :action | |
def initialize(matcher, action) | |
@matcher, @action = matcher, action | |
end | |
end | |
class SwitchBitch | |
def initialize(value, &block) | |
@value = value | |
@match_list = [] | |
instance_exec &block | |
end | |
def case_(matcher, &block) | |
@match_list << Match.new(matcher, block) | |
end | |
def breakout | |
throw :breakout | |
end | |
def find_first_match_index | |
@match_list.find_index { |m| m.matcher == @value } | |
end | |
def run | |
if !(index = find_first_match_index) | |
puts "no matches!" | |
return | |
end | |
catch :breakout do | |
@match_list[index..-1].each do |match| | |
instance_exec(&match.action) | |
end | |
end | |
end | |
end | |
def switch(value, &block) | |
SwitchBitch.new(value, &block).run | |
nil | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment