Without Book Interview Questions and Answers | Online Test | Moct Test
Download Android App in your Android Device from Google Play Store
- Search for "Withoutbook Practice Exam Test" in Mobile/Tablet Play Store
Institute Training Search by Name or Email

Exams Attended

Make Homepage

Bookmark this page

Subscribe Email Address

Ruby On Rails Interview Questions and Answers

Ques. How will you implement Single Pattern in Ruby on Rails?

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")
  def log(msg)

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.

Is it helpful? Yes No

Most helpful rated by users:

©2016 WithoutBook