From: "Mauricio Fernández" Date: 2003-03-21T01:41:05+09:00 Subject: Re: class level Exception handling On Fri, Mar 21, 2003 at 01:08:30AM +0900, Xiangrong Fang wrote: > Hi > > Could anyone teach me about the following? > > 1. in a File.open do ... end block, if I call break or return to exit > the block, will the file be closed? I guess yes, as it uses rb_ensure. > 2. Is there a way to write a class-level exception handler? See the > following: > > class A > def method 1 > begin > ... > rescue > end > end > def method 2 > begin > ... > rescue > end > end > end > > in the above code, I do a lot of TCP Socket related work in method1 > method2 etc. I would like to return false for all these methods if > there's any error, can I do better than use a begin/rescue/end for every > of them? batsman@tux-chan:/tmp$ expand -t2 < p.rb module WrapMethod def __block__(meth) @blocks[meth] end def wrap(*args, &block) @blocks ||= {} args.each do |meth| alias_method "__#{meth.to_s}__".intern, meth @blocks[meth] = block module_eval <<-EOF def #{meth.to_s}(*args,&b) begin return __#{meth.to_s}__(*args,&b) rescue Exception return self.class.__block__(:#{meth.to_s}).call end end EOF end end end class A extend WrapMethod def foo; raise "BAD THING"; end def bar; raise "and another!"; end def baz; "GOOD"; end wrap :foo, :bar, :baz do puts "Got #{$!.inspect}" false end end a = A.new puts a.foo, a.bar, a.baz batsman@tux-chan:/tmp$ ruby p.rb Got # Got # false false GOOD -- _ _ | |__ __ _| |_ ___ _ __ ___ __ _ _ __ | '_ \ / _` | __/ __| '_ ` _ \ / _` | '_ \ | |_) | (_| | |_\__ \ | | | | | (_| | | | | |_.__/ \__,_|\__|___/_| |_| |_|\__,_|_| |_| Running Debian GNU/Linux Sid (unstable) batsman dot geo at yahoo dot com Let's call it an accidental feature. --Larry Wall