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

Snippets has posted 5883 posts at DZone. View Full User Profile

Adding Virtual Methods To Ruby

09.18.2006
| 5345 views |
  • submit to reddit
        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

Manual trackback regarding this post: http://blog.evanweaver.com/articles/2006/10/03/duck-typing-and-ruby-virtual-classes

Rob Sanheim replied on Tue, 2006/07/25 - 4:11pm

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.

Snippets Manager replied on Thu, 2006/09/28 - 3:34pm

I don't get it?