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样?

解决方法

所以用户不要“记得做整个开始抢救 – 确保chacha”组合救援/确保与收益.
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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...