DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Adding Virtual Methods To Ruby
From:
http://ozone.wordpress.com/2006/02/28/adding-virtual-methods-to-ruby/
Author: Olivier Ansaldi
class VirtualMethodCalledError < RuntimeError
attr :name
def initialize(name)
super("Virtual function '#{name}' called")
@name = name
end
end
class Module
def virtual(*methods)
methods.each do |m|
define_method(m) {
raise VirtualMethodCalledError, m
}
end
end
end
# The usage is beautifully simple:
class VirtualThingy
virtual :doThingy
end
class ConcreteThingy < VirtualThingy
def doThingy
puts "Doin' my thing!"
end
end
begin
VirtualThingy.new.doThingy
rescue VirtualMethodCalledError => e
raise unless e.name == :doThingy
end
ConcreteThingy.new.doThingy






Comments
Snippets Manager replied on Tue, 2006/10/03 - 4:48pm
Rob Sanheim replied on Tue, 2006/07/25 - 4:11pm
virtualin the super class. Then if someone calls the virtual method, or doesn't implement the method in a subclass, the exception is raised. Its really just a way of doing class interfaces in Ruby.Snippets Manager replied on Thu, 2006/09/28 - 3:34pm