Singleton Spiderman

A Singleton is a pattern that ensures that a class has only one instance and provides global access to it.

Imagine we have to access our database, instead of opening a connection for each call to our DB, we could use the singleton pattern to return the same DB instance.

Let’s see how to do this manually and then let’s see the magic of Ruby:

class Database
  @instance = new

  private_class_method :new

  def self.instance
    @instance
  end

  def connect
    puts 'DB connection logic here'
  end
end

#To access the instance: 
Database.instance

The previous code makes the constructor private so it’s impossible to create multiple instances, instead we create a custom method that returns the cached instance.

Now comes the magic! 🪄 Ruby has already a module for singletons, so you can simplify the previous code to:

require 'singleton'

class Database
  include Singleton

  def connect
    puts 'DB connection logic here'
  end
end

#To use it: 
Database.instance

This and the previous code are the same.

What you saw is a simple example to understand Singletons. For multithread apps, we should implement a thread-safe approach.