Someth Victory

Ruby, Rails, and Javascript Developer

Singleton Pattern in Ruby

Singleton Pattern is a design pattern that allow a class to be instantiated only once. The benefit of Singleton is to be ensure that there is only one and the same instance of object is called every time. Ruby also support Singleton Pattern.

In order to create a singleton class in Ruby, Singleton module needs to be included.

Check out the code below:

Singleton Example
1
2
3
4
5
6
7
8
9
10
11
class OpenSRSServer
  include Singleton

  def connection
    @connection ||= OpenSRS::Server.new(
      key:      ENV['OPENSRS_ACCESS_KEY'],
      server:   ENV['OPENSRS_SERVER'],
      username: ENV['OPENSRS_REG_USERNAME']
    )
  end
end

The example above created a ruby singleton class called OpensrsServer, with an instance method called connection. This class is responsible for creating a connection object using OpenSRS gem.

In order to instantiate an object with singleton class in Ruby, we need to use .instance method rather than .new.

Singleton Object
1
server = OpenSRSSErver.instance

No matter how many time OpenSRSServer.instance get called, the object returned will be the same.