How to Write a Singleton Class in Ruby
A Singleton is a Design Pattern which is used to prevent a class from being instantiated more than once. So there can only be one object of that particular type of class.
Writing a Singleton Class in Ruby is very easy and much more straight forward than doing it in Java, for example.
It uses Ruby Mixins to prevent you from instantiating the same class more than once and allows you to get back the only instance which can ever be instantiated.
Here is an example of a Singleton Class:
Of course you need to add your own methods, but here’s the minimum set up.
require 'singleton' class TestSingleton include Singleton end
To get back the instance, and by definition ‘Singleton’ means there can only be one!:
a = TestSingleton.instance
If you try to instantiate it with new, it will fail since your class is a Singleton:
irb(main):006:0> a = TestSingleton.new NoMethodError: private method `new' called for TestSingleton:Class from (irb):6