From: ptkwt@...1.aracnet.com (Phil Tomson) Date: 2002-03-14T03:20:20+09:00 Subject: Re: Method type 'abstract' (Module#abstract) In article , Phil Tomson wrote: >In article <00e001c1c9e8$18a97940$0700000a@backpack>, >Nat Pryce wrote: >>From: "Peter Hickman" >>> At present I have to insert a normal method in the class that raises an >>> exception which will then cause the subclass to fall over if it did not >>> override it. It works but it isn't clean, to my mind abstract is just as >>> fundemental as public or private and therefore should be marked as such. >> >>Why not just *not* implement the method at all and let method_missing throw >>the exception for you? >> > >That would be a problem in classes where you define method_missing for >some other use. > >I'm content with throwing an exception in methods that are 'abstract' (ie. >methods that should be overridden by subclasses), but perhaps we can make >that easier by defining an 'abstract' method within Module, like: > The code I posted previously doesn't work, however I played with it and came up with the following code that does work: 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 MyClass abstract :some_method end mc = MyClass.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 < MyClass def some_method puts "OtherClass::some_method" end end oc = OtherClass.new oc.some_method #=> "OtherClass::some_method" Phil