Ruby编程中的错误处理与钩子机制
1. 模块方法混入优化
在Ruby中,让类同时使用 include 和 extend 来混入模块方法并非不可行,但不够优雅。其实可以一次性混入模块的所有优点。模块可以通过 included 钩子知道自己何时被类包含,利用这一点可以巧妙地混入类方法。示例代码如下:
module UsefulMethods
module ClassMethods
def a_class_method
end
end
def self.included( host_class )
host_class.extend( ClassMethods )
end
def an_instance_method
end
# Rest of the module deleted...
end
class Host
include UsefulMethods
end
2. at_exit 钩子的使用
at_exit 钩子就像是Ruby中的“死神”,仅在Ruby应用程序即将退出时起作用。它会在Ruby解释器退出前被调用,这是在程序结束前执行代码的最后机会。使用 at_exit 与其他钩子不同,只需传入一个代码块:
at_exit do
puts "Have a nic
超级会员免费看
订阅专栏 解锁全文
10

被折叠的 条评论
为什么被折叠?



