Created
July 29, 2012 09:40
-
-
Save banister/3197076 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
module FakeOverloader | |
def method_added(name) | |
return if @__flag | |
@__overloads__ ||= {} | |
@__overloads__[name] ||= {} | |
m = instance_method(name) | |
@__overloads__[name][m.arity] = m | |
@__flag = true | |
define_method(name) { |*args, &block| self.class.__overloads__[name][args.size].bind(self).call(*args, &block) } | |
@__flag = false | |
end | |
attr_reader :__overloads__ | |
end | |
[29] (pry) main: 0> class Hello | |
[29] (pry) main: 0* extend FakeOverloader | |
[29] (pry) main: 0* def test | |
[29] (pry) main: 0* puts "no args!" | |
[29] (pry) main: 0* end | |
[29] (pry) main: 0* def test(arg) | |
[29] (pry) main: 0* puts "one arg with value #{arg}" | |
[29] (pry) main: 0* end | |
[29] (pry) main: 0* def test(arg1, arg2) | |
[29] (pry) main: 0* puts "two args with values #{arg1} #{arg2}" | |
[29] (pry) main: 0* end | |
[29] (pry) main: 0* end | |
=> nil | |
[30] (pry) main: 0> h = Hello.new | |
=> #<Hello:0x007f9c62572c08> | |
[31] (pry) main: 0> h.test | |
no args! | |
=> nil | |
[32] (pry) main: 0> h.test(1) | |
one arg with value 1 | |
=> nil | |
[33] (pry) main: 0> h.test(1, 2) | |
two args with values 1 2 | |
=> nil | |
[34] (pry) main: 0> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment