-
-
Save makefunstuff/7217090 to your computer and use it in GitHub Desktop.
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 Module | |
def dispatch(*klasses, last) | |
last_klass, mid = last.first | |
klasses << last_klass | |
__dispatch_list << [klasses, instance_method(mid)] | |
define_method(mid, __dispatch_proc(__dispatch_list)) | |
end | |
def __dispatch_list | |
@__dispatch_list ||= [] | |
end | |
def __dispatch_proc(dispatch_list) | |
proc { |*args, &bk| | |
_, meth = dispatch_list.find { |klasses, meth| | |
args.size == klasses.size && args.zip(klasses).all? { |arg, klass| klass === arg } | |
} | |
raise TypeError, "bad argument types in method call" unless meth | |
meth.bind(self).call(*args, &bk) | |
} | |
end | |
end | |
class Foo | |
dispatch String, String => def bar(a, b) | |
a + b | |
end | |
dispatch Integer, Integer => def bar(a, b) | |
a * b | |
end | |
end | |
puts Foo.new.bar("hello ", "world") | |
puts Foo.new.bar(9, 9) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment