From: Daniel Schierbeck Date: 2005-11-26T22:32:28+09:00 Subject: Re: `finalize' method? ts wrote: >>>>>> "D" == Daniel Schierbeck writes: > > D> What would you call such an approach? Encapsulating? I use this often > D> enough that I think it would fit lovely in a module: > > A bad approach, at least for me. > > D> def self.new(*args) > D> yield obj = __new__(*args) > D> obj.finalize if obj.respond_to? :finalize > D> end > > There is a convention in ruby : the method ::new must return an object of > the class. You must change the name of the method if its return nil, or > another object. Roger. That's not that hard to do: module Encapsulatable def self.included(klass) super klass.metaclass_eval do private :new def encapsulate(*args) yield obj = new(*args) obj.finalize if obj.respond_to? :finalize end end end end Note that this doesn't prevent the user from calling methods on the object after its `finalize' method has been called. class Klass include Encapsulatable def initialize puts "initializing..." end def foo puts "called method `foo'" end def finalize puts "finalizing..." end end ref = nil Klass.encapsulate { |obj| obj.foo; ref = obj } ref.foo But then again, this ain't Java. If you want to, you could wreak havoc in seconds. But we're all friends, right? :) Cheers, Daniel