ruby - 我可以从基类添加派生类吗?
问题描述
我想为所有派生类添加模块。
但是写入prepend GenericFooException
所有文件很无聊。
(阴沉的语气。) 怎么写?
module GenericFooException
class FooException < StandardError; end
def perform
super
rescue FooException => e
# The truth is that rails ActiveRecord::ActiveRecordError with .cause
puts "[CATCH] #{e.class}"
end
end
module Foo
class Base
prepend GenericFooException
def perform
raise RuntimeError
end
end
end
# It is my best. but can not catch the FooException
module Foo
class Alice < Base
class AliceException < FooException; end
def perform
raise AliceException
end
end
end
# Work it.
module Foo
class Bob < Base
prepend GenericFooException
class BobException < FooException; end
def perform
raise BobException
end
end
end
Foo::Alice.new.perform #=> (exception)Foo::Alice::AliceException
Foo::Bob.new.perform #=> (output)[CATCH] Foo::Bob::BobException
解决方案
推荐阅读
- android - android.text.html (fromHtml): 渲染内联 CSS 颜色
- python - C++ boost.python 无法将 const char* 转换为 str
- python - 检查是否为二进制并转换为十进制
- python - 在python中使用win32com在工作簿中插入行不起作用
- mysql - 为什么我的密码在 mysql 中不起作用?苹果电脑
- javascript - JS 不会将导航显示属性从 none 更改为 flex
- java - 刷新到数据库 Spring JPA 时未填充字段
- angular - iframe src 中的 blob 对象
- mysql - 为 SQL 查询选择最佳索引
- android - Flutter sqflite 应用程序无法在真实的 ios 设备上运行