From: Robert Klemme Date: 2010-11-30T23:43:15+09:00 Subject: Re: class-wide begin/end blocks/exception handling On Tue, Nov 30, 2010 at 3:39 PM, Robert Klemme wrote: > On Tue, Nov 30, 2010 at 1:06 AM, David E. wrote: >> So I have a class with a lot of methods, and each method has a begin/end >> block >> >> class HiThere >>  def one(stext) >>  begin >>   puts("Hi"); >>  rescue Exception => msg >>   self.exceptionHandle(msg) >>  end >>  end >> >>  def two(stext) >>  begin >>   puts("Hi"); >>  rescue Exception => msg >>   self.exceptionHandle(msg) >>  end >>  end >> >>  #etc etc >>  #... >> end >> >> ... Is there a way to put one begin/end block encompassing the whole >> class/object? Sort of like an instance-wide begin/end block? > > Not directly, but you can do Even better class Proxy < BasicObject def initialize(obj, &handler) @obj = obj @handler = handler end def method_missing(*a,&b) @obj.send(*a,&b) rescue ::Exception => e @handler and @handler[e] end end def Proxy(obj, &handler) Proxy.new(obj, &handler) end irb(main):016:0> s = "foo" => "foo" irb(main):017:0> s + "bar" => "foobar" irb(main):018:0> s + 99 TypeError: can't convert Fixnum into String from (irb):18:in `+' from (irb):18 from /opt/bin/irb19:12:in `
' irb(main):019:0> pr = Proxy(s) {|e| p e.message} => "foo" irb(main):020:0> pr + "bar" => "foobar" irb(main):021:0> pr + 99 "can't convert Fixnum into String" => "can't convert Fixnum into String" irb(main):022:0> Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/