How to implement an abstract class in ruby? -
i know there no concept of abstract class in ruby. if @ needs implemented, how go it? tried like...
class   def self.new     raise 'doh! trying write java in ruby!'   end end  class b <   ...   ... end   but when try instantiate b, internally going call a.new going raise exception.
also, modules cannot instantiated cannot inherited too. making new method private not work. pointers?
i don't using abstract classes in ruby (there's better way). if think it's best technique situation though, can use following snippet more declarative methods abstract:
module abstract   def self.included(base)     base.extend(classmethods)   end    module classmethods     def abstract_methods(*args)       args.each |name|         class_eval(<<-end, __file__, __line__)           def #{name}(*args)             raise notimplementederror.new("you must implement #{name}.")           end         end       end     end   end end  require 'rubygems' require 'spec'  describe "abstract methods"   before(:each)     @klass = class.new       include abstract        abstract_methods :foo, :bar     end   end    "raises notimplementederror"     proc {       @klass.new.foo     }.should raise_error(notimplementederror)   end    "can overridden"     subclass = class.new(@klass)       def foo         :overridden       end     end      subclass.new.foo.should == :overridden   end end   basically, call abstract_methods list of methods abstract, , when called instance of abstract class, notimplementederror exception raised.
Comments
Post a Comment