Ruby On Rails Interview Questions and Answers
Ques. How will you implement Single Pattern in Ruby on Rails?Ans.
Singleton means single instance.
So, the goal of a singleton pattern is to write a class definition but only allow the creation of the single instance of that object.
This can be achieved nicely with the singleton gem as shown below:
require 'singleton' class Logger include Singleton def initialize @log = File.open("logfile.txt", "a") end def log(msg) @log.puts(msg) end end
Adding the singleton as a mixin to the
Logger.instance.log('This is just a test message')
The code above will create a single instance of Logger and simply put the message in the logger file.
Singleton patterns are mostly used for DB instance, Logger instance, etc. —- cases where there should be ONE and only ONE instance of the object that is used.
Sometimes you might like to actually hold on to the logger object and use it everywhere you can do so by the following command:
logObj = Logger.instance
Notice you cannot use the Logger.new to create an object instance because this is a singleton object and therefore calling ‘new’ would fail.
Most helpful rated by users: