Ruby Findings

digging for gems

Object destruction

Posted by Art Green Fri, 07 Sep 2007 17:48:00 GMT

Ruby does not provide programmer defined destruction methods. In C++ you can define a method that is messaged when the object instance is destroyed. This method can perform clean-up operations such as deleting temporary files.

Ruby, however, destroys objects dynamically during a scheduled garbage collection. This means that, during a run, it is impossible to know when an object instance will be destroyed. This fact combined with the lack of a destruction method can create headaches when there is a need to clean-up during object destruction.

Since there is no direct support for a destructor method, you must call a custom function, or more specific a proc object, when the garbage collector is about to destroy the object. As stated before it is unpredictable when this occurs.

Also if such a finalizer object has a reference to the orignal object, this may prevent the original object to get garbage collected.

Because of this problem, the finalize method below is a class method and not a instance method. So if you need to free resources for an object, like closing a socket or killing a spawned subprocess, you should do it explicitly with the ObjectSpace class.

class MyClass
  def initialize
    ObjectSpace.define_finalizer(self,
     self.class.method(:finalize).to_proc)
  end

  def MyClass.finalize(id)
    puts "Object #{id} dying at #{Time.new}"
  end
end

# test code
3.times {
    MyClass.new
}
ObjectSpace.garbage_collect

Posted in | no comments |

Multiple class initialization methods

Posted by Art Green Thu, 06 Sep 2007 01:18:00 GMT

Here’s a quick run-down on the development of multiple initialize methods for Ruby classes: Multiple Initialize Methods.

The author looks at the subject from a domain language idiom perspective. I used the information to provide multiple creation interfaces for a class.

Quick example:

Class Archive
  def Archive.create( archive_name )
    return self.new( archive_name, :create )
  end

  def Archive.open( archive_name )
    return self.new( archive_name, :open )
  end

  def initialize( archive_name, mode )
    # do interesting stuff
  end
end

arch = Archive.open("some_existing_file")
arch = Archive.create("some_new_file")

Posted in , | no comments |

Older posts: 1 2