Ruby/Class/abstract class

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

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



Creating an Abstract Class and Method

class Shape2D
  def initialize
    raise NotImplementedError.
      new("#{self.class.name} is an abstract class.")
  end
  def area
    raise NotImplementedError.
      new("#{self.class.name}#area is an abstract method.")
  end
end
 
class Square < Shape2D
  def initialize(length)
    @length = length
  end
  def area
    @length ** 2
  end
end
Square.new(10).area                              # => 100
# NotImplementedError: Shape2D is an abstract class.