【发布时间】:2018-11-27 02:27:00
【问题描述】:
基本上,这是正常的代码:
class Foo
def hi
# your code here....
rescue => e
# Raise error here
end
def hello
# your code here...
rescue => e
# Raise error here
end
end
但在 PHP 中,我可以使用__call 魔术方法创建抽象类,如下所示:
class FooAbstract {
public function __call($name, $args) {
# Try catch in here...
}
}
class Foo extends FooAbstract {
public function hi() {
# Code with try catch...
}
}
如何在 Ruby 类中使用 __call 方法???
【问题讨论】:
-
如果你想定义一个类,除非是子类,否则它不能被实例化,你可以在 FooAbstract#initialize 中做一个
fail "Trying to instantiate abstract class" if self.class == FooAbstract。 -
这看起来像是一个 XY 问题。你想完成什么?
-
ruby 中没有与
__call等效的direct;最接近的可能是method_missing。 (同样,在 PHP 中没有与method_missing等效的 direct,但据我所知,__call可能是最接近的。)但正如 Stefan 所说,你实际上想在这里实现什么?在不知道您要解决什么问题的情况下,我无法真正建议如何构建代码。 -
我的猜测是完成类似rails类级别
rescue_from这样的事情,这样您就不必将相同的rescue块复制粘贴到每个方法中。 -
不确定你想用那个 PHP 代码说明什么,但是方法
hi不会以任何方式调用__call。__call应该做什么,为子类的所有方法添加异常处理?
标签: ruby