In article <5174eed0.0210151939.2ad2deb1 / posting.google.com>,
Edward Wilson <web2ed / yahoo.com> wrote:
>Is there a way to write/inforce interfaces in Ruby like one can using
>Abstract Classes in C++ or Interfaces in Java?
>
>If not, how has everyone been approaching this?
>
>//ed

How about:

class AbstractException < Exception
end

class Module
  def abstract(*methods)
    methods.each { |s|
      class_eval("def #{s}; raise AbstractException,'#{s} should be 
overriden!'; end")
    }
  end
end

class MyAbstractClass
  abstract :some_method
end

mc = MyAbstractClass.new
mc.some_method
#end

Now if you run this you'll get:

(eval):1:in `some_method': some_method should be overriden! 
(AbstractException) from abstract.rb:23

Now you can create a subclass of MyClass and override 'some_method', like:

class OtherClass < MyAbstractClass
  def some_method
    puts "OtherClass::some_method"
  end
end

oc = OtherClass.new
oc.some_method #=> "OtherClass::some_method"


(Actually, I posted this code before back in March)

Phil