From: Robert Klemme Date: 2010-11-30T23:39:23+09:00 Subject: Re: class-wide begin/end blocks/exception handling 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 # needs 1.9 class Proxy < BasicObject def initialize(obj) @obj = obj end def method_missing(*a,&b) @obj.send(*a,&b) rescue ::Exception => e handle_exception e end def handle_exception(e) puts e.message end 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.new(s) => "foo" irb(main):020:0> pr + "bar" => "foobar" irb(main):021:0> pr + 99 can't convert Fixnum into String => nil irb(main):022:0> HTH Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/