Fantastic.  I was going to suggest making it a mixin, but you beat me to it
:-)  It would be good as part of the standard library.  I would go as far as
to make the close method mandatory, so that new/close is a standard protocol
for objects that control resources outside the interpreter.  Having a
standard protocol for accessing and closing resources will allow us to write
generic code that uses resources, such as your mixin.

Finally, instead of 'return yield(obj)' shouldn't it be 'return
block.call(obj)' ?

Cheers,
        Nat.

----- Original Message -----
From: "Dave Thomas" <Dave / PragmaticProgrammer.com>
> "Nat Pryce" <nat.pryce / b13media.com> writes:
>
> > Ruby uses blocks to scope resource allocation and deallocation to scopes
,
> > just like C++ does with constructors/destructors.  Look at the
File::open
> > method for an example.
>
> I liked Nat's idea a lot, so how about this:
>
>      module Resource
>        def Resource.append_features(to)
>          def to.use(*params, &blk)
>            obj = new(*params, &blk)
>            begin
>              return yield(obj)
>            ensure
>              obj.close if obj.respond_to?(:close)
>            end
>          end
>        end
>      end
>
> Then you simply say
>
>      class Dave
>        include Resource
>
>        # rest of class
>      end
>
> From then on, you can use a block for objects of class Dave. A 'close'
> method will get called automatically at the end if it exists
>
>      Dave.use do |d|
>        # ...
>      end
>
>
>
> Dave (hoping to see some of you next week at JAOO)
>