From: "Ara.T.Howard" Date: 2005-11-02T02:58:11+09:00 Subject: Re: Best way to free a device On Wed, 2 Nov 2005, Detlef Reichl wrote: > Hi, > > what is the best way to release an unix device that can't handle > multiple opens? > > I've created a video device class in C, where the device gets opened > with an instanciation like: > > Wc::Cam.new '/dev/video0' > > In this class i also added a destructor that closes the device. But it > is called to late. From > > http://www.rubygarden.org/ruby?ResourceAcquisitionIsInitialization > > i've seen, that i cant aspect a direct destruction of the object if it's > not more in use. > > Is there a more elegant way to free the resources automatically, as to > create a special free or close method for my object? make 'Wc::Cam::new' return a singleton object and allow new to take a block that cleans up. module Wc class Cam INSTANCES = {} def new path cam = if INSTANCES.has_key? path return INSTANCES[path] else super end if block_given? begin yield cam ensure cam.close end else cam end end end end that way you can write Wc::Cam::new('/dev/video0') do |cam| end and ensure the cam is closed. when blocks dont' suffice you can write a = Wc::Cam::new '/dev/video0' b = Wc::Cam::new '/dev/video0' and both a and b will be the same object. regards. -a -- =============================================================================== | email :: ara [dot] t [dot] howard [at] noaa [dot] gov | phone :: 303.497.6469 | anything that contradicts experience and logic should be abandoned. | -- h.h. the 14th dalai lama ===============================================================================