在 Ruby (Rails) 中模拟抽象类 [英] Simulating abstract classes in Ruby (Rails)

查看:36
本文介绍了在 Ruby (Rails) 中模拟抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Ruby on Rails 中模拟一个抽象类.IE.如果有人尝试调用 Abstract.new,我想引发异常,但他应该能够调用 Child.new(而 Child 代码>).

I want to simulate an abstract class in Ruby on Rails. I.e. I want to raise an exception if someone tries to call Abstract.new, but he should be able to call Child.new (while Child < Abstract).

如何做到这一点?覆盖 newinitialize 不起作用.

How to do this? Overwriting both new and initialize does not work.

推荐答案

为什么要这样做?抽象/接口类的重点是将强类型语言破解为动态范式.如果您需要您的类适合签名,根据原始类命名您的方法或创建一个外观并将其插入,无需欺骗编译器允许它,它就可以工作.

Why would you want to do this? The point of abstract/interfaced classes are to hack Strongly typed languages into a dynamic paradigm. If you need your class to fit in the signature, name your methods according to the original class or make a facade and plug it in, no need to trick a compiler into allowing it, it just works.

def my_printer obj
  p obj.name
end

所以我将接口定义为具有名称属性的任何对象

So I defined the interface as any object with a name property

class person
  attr_accessor :name
  def initialize
   @name = "Person"
  end
end

class Employee
   attr_accessor :name
  def initialize
   @name = "Employee"
   @wage = 23
  end
end

所以没有什么能阻止我们使用其中任何一个调用我们的打印机方法

so nothing stops us from calling our printer method with either of these

my_printer Person.new
my_printer Employee.new

两者都在那里顺利打印名称:D

both print there names without a hitch :D

这篇关于在 Ruby (Rails) 中模拟抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆