From: Robert Klemme Date: 2007-09-11T17:55:17+09:00 Subject: Re: Singleton Modules rather than Singleton Classes 2007/9/1, Trans : > This recently came up in the thread entitled "Python-style > Decorators", so I thought it a fair idea to "formally" put it before > the Ruby community. Here's the deal... > > Singleton classes already have more in common with modules than > classes by the very behaviors that distinguish a module from a class -- > they cannot be instantiated and they can not be inherited. So why > exactly do we deem them classes at all? If instead we took them to be > actual modules, and used as such, it would open up some really nice > possibilities. For example: > > class A > def self.x > "x" > end > end > > class B > extend (class << A; self; end) > end > > B.x #=> "x" > > This makes it dead simple to pass along module class-level methods in > the class hierarchy. The immediate use of this change is apparent --no > more ClassMethods/included callback hacks required. You do not need that, because the functionality is there already: $ ruby < class A > def self.x > "x" > end > end > class B < A; end > p B.x > XXX "x" > One thing to note about this example, the notation "(class << A; self; > end)" becomes a bit of a misnomer in light of the suggested change. > "A.singleton" or some other method name, would be far better. > > Another possibility, which derives from the aforementioned thread, are > method decorators using singleton def notation: > > class Example > > def memoized.foo > ... > end > > end > > It is not possible to meta-code this currently b/c the definition of > foo gets locked away in a singleton class where it can not be reused. > If that singleton could be included into a class (in this case > Example) then presto, problem solved, and a powerful new notation is > opened up to the Ruby programmer. I'd generally prefer to define modules explicitly and extend classes with them as Ara suggested. IMHO that's a cleaner way to achieve what you want and it also documents things more nicely (especially you can look at inheritance etc.). My 0.02EUR Kind regards robert