Wednesday 17 May 2017

Singleton Design pattern in rails

Singleton is a design pattern that restricts instantiation of a class to only one instance that is globally available. It is useful when you need that instance to be accessible in different parts of the application, usually for logging functionality, communication with external systems, database access, etc.

Single Instance of a class

class Logger
  def initialize
    @log = File.open("log.txt", "a")
  end

  @@instance = Logger.new

  def self.instance
    return @@instance
  end

  def log(msg)
    @log.puts(msg)
  end

  private_class_method :new
end

Logger.instance.log('message 1')


In this code example, inside class Logger we create instance of the very same class Logger and we can access that instance with class method Logger.instance whenever we need to write something to the log file using the instance method log. In the initialize method we just opened a log file for appending, and at the end of Logger class, we made method new private so that we cannot create new instances of class Logger. That is Singleton Pattern: only one instance, globally available.

Ruby Singleton module

Ruby Standard Library has a Singleton module which implements the Singleton pattern. Previous example when using the Singleton module would translate to:

require 'singleton'

class Logger
  include Singleton

  def initialize
    @log = File.open("log.txt", "a")
  end

  def log(msg)
    @log.puts(msg)
  end
end

Logger.instance.log('message 2')
Here we require and include Singleton module inside Logger class, define initialize method which opens the log file for appending and instance method log for writing to that log file. Ruby Singleton module does lazy instantiation (creates instance from Logger class at the moment when we call Logger.instance method) and not during load time (like in the previous example). Also, Ruby Singleton module makes new method private, so we don't have to call private\_class\_method.


2 comments:

  1. Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking.keep updating blogger.
    Ruby on Rails Online Training india

    ReplyDelete