大佬教程收集整理的这篇文章主要介绍了Ruby中的RAII(或者,如何管理Ruby中的资源),大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
然而,C的RAII是Ruby的成语(资源在构造函数中初始化,在析构函数中关闭)?即使发生错误或异常,人们如何管理在对象内部使用的资源?
使用确保作品:
f = File.open("testfile") begin # .. process rescue # .. handle error ensure f.close unless f.nil? end
但是该类的用户必须记住,每次开放方法需要被调用时,都要进行整个开始抢救 – 确保chacha.
所以例如,我将有以下类:
class SomeResource def initialize(connection_string) @resource_handle = ...some mojo here... end def do_something() begin @resource_handle.do_that() ... rescue ... ensure end def close @resource_handle.close end end
如果异常是由某个其他类引起的,并且脚本退出,那么resource_handle将不被关闭.
还是更多的问题我还在做这样的C样?
class SomeResource ... def SomeResource.use(*resource_args) # create resource resource = SomeResource.new(*resource_args) # pass args direct to constructor # export it yield resource rescue # known error processing ... ensure # close up when done even if unhandled exception thrown from block resource.close end ... end
客户端代码可以使用如下:
SomeResource.use(connection_string) do | resource | resource.do_something ... # whatever else end # after this point resource has been .close()d
事实上,这是File.open如何运作 – 使第一个答案最大的困惑(就是我的同事们).
File.open("testfile") do |f| # .. process - may include throwing exceptions end # f is guaranteed closed after this point even if exceptions are # thrown during processing
以上是大佬教程为你收集整理的Ruby中的RAII(或者,如何管理Ruby中的资源)全部内容,希望文章能够帮你解决Ruby中的RAII(或者,如何管理Ruby中的资源)所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。