From: James Edward Gray II Date: 2007-07-12T22:32:47+09:00 Subject: Re: Abstract methods in ruby ? On Jul 12, 2007, at 7:05 AM, Robert Dober wrote: > On 7/12/07, James Edward Gray II wrote: >> On Jul 11, 2007, at 5:40 PM, cypher.dp@gmail.com wrote: >> >> > How do you implement something like the "abstract" keyword in >> Java ? >> > Or: Is there a technique to force a subclass to implement a special >> > method ? >> >> One way is: >> >> class Parent >> def abstract_method >> raise NotImplementedError >> end >> end >> >> You may just want to skip this step altogether though, since an >> exception toss is the default behavior. > > Hmm, I would say no, you will be caught by #method_missing one day. > It would be interesting why you want to do this? If someone adds a method_missing() implementation to a child class that accepts messages it shouldn't, there is a bug in that implementation and it needs to be fixed. Your tests are going to catch that for you. > For documentation purpose? That is about the best reason to add the stub, I think. > If you are looking for warnings or errors for subclasses not > implementing the abstract method you will be disappointed at Compile > Time [which arguabley does not even exist in 1.8] class AbtractClass REQUIRED_METHODS = %w[one two three] def self.inherited(subclass) REQUIRED_METHODS.each do |m| raise "An implementation of #{m} is required by #{self.class}" \ unless subclass.instance_methods.include? m end end end class Broken < AbtractClass def one; end def two; end end # ~> -:7:in `inherited': An implementation of one is required by Class (RuntimeError) # ~> from -:5:in `each' # ~> from -:5:in `inherited' # ~> from -:12 But don't do that. ;) James Edward Gray II