Never been to DZone Snippets before?

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 (See related posts)

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 on this post

Adkron posts on Sep 28, 2006 at 15:37
I don't get it?
rsanheim posts on Sep 29, 2006 at 03:34
I believe its creating the equivalent of an abstract method in Java. So if you have methods that subclasses have to implement, you declare them
virtual
in 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.
evn posts on Oct 04, 2006 at 06:44
Manual trackback regarding this post: http://blog.evanweaver.com/articles/2006/10/03/duck-typing-and-ruby-virtual-classes

You need to create an account or log in to post comments to this site.


Click here to browse all 5141 code snippets

Related Posts