Handling cases where there can be only one
In cases where an application using your library should only have a single instance of the object, you usually would reach for the singleton design pattern. Ruby actually has a standard library for the singleton pattern, appropriately named singleton
. This library defines the Singleton
module, which you can include in other classes to turn those classes into singletons. A class that includes Singleton
no longer has a public new
method, since you should not be creating multiple instances. Instead, it provides a class method named instance
, which returns the only instance of the class:
require 'singleton' class OnlyOne   include Singleton   def foo     :foo   end end   only1 = OnlyOne.instance only2 = OnlyOne.instance only1.equal?(only2) # => true
The singleton
library does implement the singleton pattern. So why wasn't it discussed in the previous section,...