Over a million developers have joined DZone.

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


Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}