From: Rich Kilmer Date: 2002-05-02T12:18:28+09:00 Subject: RE: Scope of Singleton Classes See comment below: > -----Original Message----- > From: Jason Voegele [mailto:jason@jvoegele.com] > Sent: Wednesday, May 01, 2002 3:03 PM > To: ruby-talk ML > Subject: Scope of Singleton Classes > > I'm writing an object proxy that intercepts method calls with > method_missing > and then forwards them to another object for handling. I want to avoid > the > overhead of using method_missing every time, so I'd like to define a new > method each time method_missing is invoked that actually does the > forwarding. I have a few questions about this approach. > > I tried something like this: > > class ObjectProxy > def method_missing(operation, *args) > class << self > define_method(operation, args) do |opargs| > forward(*opargs) > end > end > end > > def forward(operation, *args) > # call operation on target object > end > end > > 1) I was surprised to learn that the singleton class defined by "class << > self" does not have access to local variables in its lexical scope (e.g. > "operation" and "args"). Is this by design? > > 2) Is there solution that utilizes define_method rather than eval? > > 3) Is caching methods like this (rather than relying on method_missing for > each invocation) a significant enough performance improvement to make it > worth it? Because the method you define to "cache" ends up calling the #forward method, I can't see how this would be different than performance of calling #forward from method_missing. One other thing to remember in your ObjectProxy is that method_missing will not be called for methods that are defined (or included from Modules) in Object which is quite a list. You may want to "undef" all the inherited methods. > > Thanks, > -- > Jason Voegele > "We believe that we invent symbols. The truth is that they invent us." > -- Gene Wolfe, The Shadow of the Torturer