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:
- Unique Instance: The
Singletonmodule ensures that only one instance of the class exists. The instance is created wheninstanceis called for the first time. - Global Access: The singleton instance can be accessed globally through the
instancemethod. - Thread-Safe: The
Singletonmodule is designed to be thread-safe, making it suitable for multi-threaded applications.
Use Cases:
- Configuration Management: Managing application-wide configuration settings.
- Logger: Creating a single logging instance that is used throughout the application.
- Cache: Managing a global cache that stores frequently accessed data.