在 Ruby (Rails) 中模拟抽象类

编程入门 行业动态 更新时间:2024-10-27 04:36:15
本文介绍了在 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).

如何做到这一点?覆盖 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) 中模拟抽象类

本文发布于:2023-10-31 05:42:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545179.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:抽象类   Ruby   Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!