From: "Mauricio Fernández" Date: 2002-10-17T00:24:26+09:00 Subject: Re: Hooking on method invocation On Wed, Oct 16, 2002 at 11:17:58PM +0900, Mauricio Fern�ndez wrote: > On Wed, Oct 16, 2002 at 10:43:05PM +0900, Eugene Zaikonnikov wrote: > > Hello, > > > > Is there a way to hook on invocation of *any* instance method of an > > object? > > > > My first attempt was to override the send method: > > > > class Foo > > #just ban them > > def send(symbol, *args) > > puts "blocked" > > end > > end > > > > It works when I do: > > > > foo = Foo.new > > foo.send :something > > > > But it has no effect on "conventional" method invocations. It seems > > that send is not a part of the built-in method dispatch procedure. > > > > I want such functionality to implement 'write barriers' for certain > > objects. The idea was to track invocation of writer methods and notify > > object's observer of changes. If this is achievable by other means, > > any hints will be greatly appreciated. > > Delegation maybe? Code follows: module Observable # pretty lame and useless, but I didn't feel like removing it after all this # typing; it could probably automate the generation of the list in a # sensible way def get_method_list [ ] end end class BarrierKeeper def initialize(obj) @theobj = obj end def method_missing(sym,*args) h = @theobj.get_method_list ret = true ret = h[sym].call if h[sym] @theobj.send(sym, *args) if ret end end class AnObject include Observable def initialize @block_proc = proc { puts "ACTION: Blocked!"; false } @notify_proc = proc do puts "ACTION: notify the observers; w/ 'require \"observer\"'" true end end def amethod puts "METH: You won't see this" end def another puts "METH: This one is not blocked." end def get_method_list { :amethod => @block_proc, :another => @notify_proc } end end a = AnObject.new theproxy = BarrierKeeper.new a theproxy.amethod theproxy.another -- _ _ | |__ __ _| |_ ___ _ __ ___ __ _ _ __ | '_ \ / _` | __/ __| '_ ` _ \ / _` | '_ \ | |_) | (_| | |_\__ \ | | | | | (_| | | | | |_.__/ \__,_|\__|___/_| |_| |_|\__,_|_| |_| Running Debian GNU/Linux Sid (unstable) batsman dot geo at yahoo dot com Q: What's the big deal about rm, I have been deleting stuff for years? And never lost anything.. oops! A: ... -- From the Frequently Unasked Questions