I\'m trying to write the most secure singleton in Ruby that I can. I\'m new to the language, which is so elastic that I don\'t have a strong feeling that my singleton class wil
# require singleton lib
require 'singleton'
class AppConfig
# mixin the singleton module
include Singleton
# do the actual app configuration
def load_config(file)
# do your work here
puts "Application configuration file was loaded from file: #{file}"
end
end
conf1 = AppConfig.instance
conf1.load_config "/home/khelll/conf.yml"
#=>Application configuration file was loaded from file: /home/khelll/conf.yml
conf2 = AppConfig.instance
puts conf1 == conf2
#=>true
# notice the following 2 lines won’t work
AppConfig.new rescue(puts $!)
#=> new method is private
# dup won’t work
conf1.dup rescue(puts $!)
#=>private method `new’ called for AppConfig:Class
#=>can’t dup instance of singleton AppConfig
So what does ruby do when you include the singleton module inside your class?
new
method private and so you can’t use it.So to use ruby singleton module you need two things:
singleton
then include it inside the desired class.instance
method to get the instance you need.