Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Destructors?

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?

like image 378
Joern Akkermann Avatar asked May 10 '11 20:05

Joern Akkermann


People also ask

What are destructors used for?

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.

Why are destructors called?

Destructors are called when one of the following events occurs: A local (automatic) object with block scope goes out of scope. An object allocated using the new operator is explicitly deallocated using delete . The lifetime of a temporary object ends.

How many arguments do destructors have?

There are specific rules that make an overloaded delete function a destructor function: the function must have just one input argument, which is an object of the class, and it must not have any output arguments.

Do destructors have parameters?

It never takes any parameters, and it never returns anything. You can't pass parameters to the destructor anyway, since you never explicitly call a destructor (well, almost never).


1 Answers

@edgerunner's solution almost worked. Basically, you cannot create a closure in place of the define_finalizer call since that captures the binding of the current self. In Ruby 1.8, it seems that you cannot use any proc object converted (using to_proc) from a method that is bound to self either. To make it work, you need a proc object that doesn't capture the object you are defining the finalizer for.

class A   FINALIZER = lambda { |object_id| p "finalizing %d" % object_id }    def initialize     ObjectSpace.define_finalizer(self, self.class.method(:finalize))  # Works in both 1.9.3 and 1.8     #ObjectSpace.define_finalizer(self, FINALIZER)                    # Works in both     #ObjectSpace.define_finalizer(self, method(:finalize))            # Works in 1.9.3   end    def self.finalize(object_id)     p "finalizing %d" % object_id   end    def finalize(object_id)     p "finalizing %d" % object_id   end end  a = A.new a = nil  GC.start 
like image 148
Su Zhang Avatar answered Sep 18 '22 13:09

Su Zhang