From: Gavin Sinclair Date: 2003-07-19T22:11:33+09:00 Subject: [Patch] FTP.new with block Hi, I've modified lib/net/ftp.rb (not committed, obviously) so that FTP.new and FTP.open are like their File counterparts: they accept a block, pass in the ftp object, and ensure the FTP connection is closed at the end of (or premature exit from) the block. Here is the extent of my testing: irb(main):001:0> irb(main):002:0* require 'net/ftp' => true irb(main):003:0> Net::FTP.open('ftp.ruby-lang.org') do irb(main):004:1* |ftp| irb(main):005:1* ftp.login 'anonymous', 'guest' irb(main):006:1> ftp.chdir 'pub/ruby' irb(main):007:1> puts ftp.ls irb(main):008:1> end drwxr-xr-x 2 1001 users 4096 Jul 17 1998 1.0 drwxr-xr-x 2 1001 users 4096 Oct 7 1997 1.1a drwxr-xr-x 2 1001 users 4096 Jul 16 1998 1.1b [...] drwxrwxr-x 2 1001 staff 4096 Jun 26 03:19 snapshots lrwxrwxrwx 1 1001 users 3 Apr 5 2001 stable -> 1.6 -rw-r--r-- 1 1001 users 995195 Jul 18 19:00 stable-snapshot.tar.gz => #, @passive=false, @mon_waiting_queue=[]> irb(main):009:0> Patch follows signoff. Gavin Index: ftp.rb =================================================================== RCS file: /src/ruby/lib/net/ftp.rb,v retrieving revision 1.17 diff -u -r1.17 ftp.rb --- ftp.rb 13 Jun 2003 00:26:51 -0000 1.17 +++ ftp.rb 19 Jul 2003 13:08:09 -0000 @@ -87,8 +87,8 @@ # # A synonym for +FTP.new+, but with a mandatory host parameter. # - def FTP.open(host, user = nil, passwd = nil, acct = nil) - new(host, user, passwd, acct) + def FTP.open(host, user = nil, passwd = nil, acct = nil, &block) # :yield: ftp + new(host, user, passwd, acct, &block) end # @@ -96,7 +96,10 @@ # is made. Additionally, if the +user+ is given, the given user name, # password, and (optionally) account are used to log in. See #login. # - def initialize(host = nil, user = nil, passwd = nil, acct = nil) + # If a block is given, it is passed the +FTP+ object, which will be closed + # when the block finishes, or when an exception is raised. + # + def initialize(host = nil, user = nil, passwd = nil, acct = nil) # :yield: ftp super() @binary = true @passive = false @@ -108,6 +111,13 @@ if user login(user, passwd, acct) end + end + if block_given? + begin + yield self + ensure + close + end end end