From: Charles Oliver Nutter Date: 2010-03-16T03:53:13+09:00 Subject: Singleton methods without the singleton class Hi all! 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. - Charlie