A Brief Introduction to Singleton

In Ruby on Rails, the Singleton module is part of the Ruby standard library and is used to enforce that a class has only one instance and provide a global point of access to that instance. This is useful in scenarios where you need exactly one object to coordinate actions across the system.

Here’s how it works and how you can use it:

How the Singleton Module Works

The Singleton module ensures that only one instance of a class can be created. When the instance method is called on the class, it either creates a new instance (if none exists) or returns the existing instance.

Using the Singleton Module

To use the Singleton module in your class, you need to include the module and then use the instance method to get the singleton instance.

Here’s an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
require 'singleton'

class ConfigurationManager
  include Singleton

  attr_accessor :configuration

  def initialize
    @configuration = {}
  end
end

# Usage:
config_manager = ConfigurationManager.instance
config_manager.configuration[:setting1] = 'value1'

# Attempting to create a new instance using `new` will raise an exception:
# config_manager = ConfigurationManager.new  # This will raise an error

# Accessing the singleton instance again:
config_manager2 = ConfigurationManager.instance
puts config_manager2.configuration[:setting1]  # Output: value1

Key Points:

  1. Unique Instance: The Singleton module ensures that only one instance of the class exists. The instance is created when instance is called for the first time.
  2. Global Access: The singleton instance can be accessed globally through the instance method.
  3. Thread-Safe: The Singleton module is designed to be thread-safe, making it suitable for multi-threaded applications.

Use Cases: