What is the correct way to write a singleton pattern in Ruby?

前端 未结 3 1018
心在旅途
心在旅途 2021-01-30 11:31

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

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-30 12:05

    # 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?

    1. It makes the new method private and so you can’t use it.
    2. It adds a class method called instance that instantiates only one instance of the class.

    So to use ruby singleton module you need two things:

    1. Require the lib singleton then include it inside the desired class.
    2. Use the instance method to get the instance you need.

提交回复
热议问题