From: Intransition Date: 2010-03-23T03:44:17+09:00 Subject: Re: Singleton methods without the singleton class On Mar 15, 2:53 pm, Charles Oliver Nutter wrote: > JRuby currently allows you to add singleton methods to normal Java > objects like this: > > foo = java.lang.String.new('blah') > def foo.bar >   # do something > end > > Unfortunately, this feature requires us to keep a weak table of all > the Java objects that enter Ruby space, since we can't attache this > singleton method directly to the object itself. I would like to > eliminate this feature at some point, but I recognize that since > people are using it we need an alternative. > > So I've hacked together a short script that provides a "Singletonizer" > module that can simulate singleton methods without actually creating a > new singleton class: > > http://gist.github.com/333174 > > The basic idea is to go ahead and add the method to the actual class, > but add it via a hashed lookup on a per-instance basis. Objects which > have had the method added will have a corresponding entry in their > attached_methods table. Objects that don't will raise NoMethodError as > usual. > > Thoughts? Comments? This version is obviously not threadsafe, but it > gets you pretty close to singleton methods without requiring singleton > classes. How do you handle #extend? I've always thought it would be wise if singleton methods were added to an anonymous module rather then directly to the object.* Perhaps taking this approach will work for JRuby. While not exactly like MRI it should be close enough for all practical purposes. (* Which is why Facets extends the #extend method to do exactly that if you supply it a block.)