加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby中的RAII(或者,如何管理Ruby中的资源)

发布时间:2020-12-16 21:47:41 所属栏目:百科 来源:网络整理
导读:我知道这是设计,你不能控制当一个对象被破坏时会发生什么.我也知道定义一些类方法作为终结者. 然而,C的RAII是Ruby的成语(资源在构造函数中初始化,在析构函数中关闭)?即使发生错误或异常,人们如何管理在对象内部使用的资源? 使用确保作品: f = File.open("
我知道这是设计,你不能控制当一个对象被破坏时会发生什么.我也知道定义一些类方法作为终结者.

然而,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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读