Ruby:析构函数? [英] Ruby: Destructors?

查看:154
本文介绍了Ruby:析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶尔需要在缓存目录中使用rmagick创建图像。



要快速删除它们,而又不丢失它们,我想删除它们



我必须改写哪种ClassMethod才能为析构函数提供代码?



我必须重写哪种ClassMethod才能为析构函数提供代码?



p>

解决方案

您可以使用 ObjectSpace.define_finalizer ,当您创建图像文件时,当垃圾回收者来收集图像文件时,它将被调用。请注意不要在proc中引用该对象本身,否则垃圾回收人员将不会收集该对象。 (不会捡起活着的东西)

  class MyObject 
def generate_image
image = ImageMagick.do_some_magick
ObjectSpace.define_finalizer(self,proc {image.self_destruct!})
结束
结束


I need to occasionaly create images with rmagick in a cache dir.

To then get rid of them fast, without loosing them for the view, I want to delete the image-files while my Ruby Instance of the Image-Class get's destructed or enters the Garbage Collection.

What ClassMethod must I overwrite to feed the destructor with code?

解决方案

You can use ObjectSpace.define_finalizer when you create the image file, and it will get invoked when the garbage man comes to collect. Just be careful not to reference the object itself in your proc, otherwise it won't be collected by the garbage man. (Won't pick up something that's alive and kicking)

class MyObject
  def generate_image
    image = ImageMagick.do_some_magick
    ObjectSpace.define_finalizer(self, proc { image.self_destruct! })
  end
end

这篇关于Ruby:析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆