我想在 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).
如何做到这一点?覆盖 new 和 initialize 不起作用.
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) 中模拟抽象类
发布评论