From: Gregory Seidman Date: 2007-08-16T01:38:47+09:00 Subject: Re: Singleton or full static class On Thu, Aug 16, 2007 at 01:00:51AM +0900, Frank Meyer wrote: > In other languages I'm using the singleton pattern when I need a > globally accessible object. But in Ruby so much is an object or behaces > like an object (or can be treated as an object) I'm not sure if I should > use the singleton pattern or make all methods to class methods and use > class variables. The Singleton pattern is usually a design mistake anyway. See http://www.adrianmccarthy.com/blog/?p=53 for a good explanation. That said... > What is the best practise in ruby? ...there is a good way of dealing with such things in Ruby. Consider a situation in which you think you need a singleton. What you really need is a handle to some object on which you can call a method (arguably you just need the method, but if there are enough of them then it pollutes the global namespace, so let's assume you need an object). We'll call the object foo_handler: module Kernel def foo_handler ::Kernel.foo_handler end def self.foo_handler @foo_handler ||= FooHandler.new end end You now have a (lazy-loading) singleton, which is stored in the Kernel object (i.e. the object representing the Kernel module). Any time you need access to it, you call foo_handler (in whatever context). Of course, if and when it should no longer be a singleton you can change the implementation of the method in Kernel without disrupting the rest of your code. You can also omit the first method entirely and simply call ::Kernel.foo_handler explicitly, which gives you the same flexibility without polluting the global namespace at all. Furthermore, using Kernel is only an example; there is nothing special about a method on the Kernel object that wouldn't work just as well as a method on some other constant. After all, constant names are nothing more than a directory service, in the same way that a filesystem can be thought of as a database. > Turing. --Greg