Mega Code Archive

 
Categories / Ruby / Class
 

Add method to class to create abstract method dynamically

class Class   def abstract(*args)     args.each do |method_name|       define_method(method_name) do |*args|         if method_name == :initialize           msg = "#{self.class.name} is an abstract class."         else           msg = "#{self.class.name}##{method_name} is an abstract method."         end         raise NotImplementedError.new(msg)      end     end   end end class Animal   abstract :initialize, :move end class Dog < Animal   def initialize     @type = :Dog   end end dog = Dog.new dog.move class Cat < Animal   def initialize     @type = :Cat   end   def move     "Running!"   end end puts Cat.new.move class Dog   def move     "walk!"   end end puts dog.move