I’ve been learning the ins and outs of the metaclass. That sounds cool, but it’s badly named: the term singleton class succinctly describes the concept. To prove my Ruby fu, I decided to implement Polymorphisms in Ruby. The hole is this:
class Test
def a
puts "Hello World"
end
def a(p)
puts "Hello #{p}"
end
end
test = Test.new
test.a
…will choke, because unlike C++, Ruby doesn’t understand multiple definitions of functions. It just redefines them, so as soon as the second function a is defined, the first is overwritten. (And since the second definition has a required parameter, changing its arity, the compiler intepreter chokes.)
Enter Morphable. Include this in your class, and methods automatically polymorph depending on their arity. self.included, self.method_added, and method_missing voodoo. There’s no tests (no TDD for me, yet) and no benchmarks (although with the amount of wizardry going on, it’ll be slower). It’ll also for sure break complex meta programming in your own classes 🙂
Refactored:
#!/usr/bin/env ruby
require 'morphable'
class Test
include Morphable
def a
puts("Vishnu Gopal")
end
def a(love)
puts love
end
def add
puts "No numbers given!"
end
def add(a, b)
a + b
end
end
test = Test.new
test.a
test.a("Love me blind!")
test.add
puts test.add(100, 200)
Download Morphable here. [I’m in the process of setting up a public Subversion/Trac repository. That’ll be available soon].
Leave a Reply