ruby - create singleton with parameters?

前端 未结 5 911
情深已故
情深已故 2021-02-05 08:17

I\'ve seen how to define a class as being a singleton (how to create a singleton in ruby):

require \'singleton\'

class Example
  include Singleton
end
         


        
5条回答
  •  攒了一身酷
    2021-02-05 09:00

    Simple singleton that doesn't depend on Singleton module

    class MyLogger
      def self.instance(filepath = File.join('some', 'default', 'path'))
        @@instance ||= new(filepath).send(:configure)
      end
    
      def initialize(filepath)
        @filepath = filepath
      end
      private_class_method :new
    
      def info(msg)
        puts msg
      end
    
      private
    
      def configure
        # do stuff
        self
      end
    end
    

    Example usage

    logger_a = MyLogger.instance
    # => #
    
    logger_b = MyLogger.instance
    # => #
    
    logger_a.info logger_a.object_id
    # 70125579507760
    # => nil
    
    logger_b.info logger_b.object_id
    # 70125579507760
    # => nil
    
    logger_c = MyLogger.new('file/path')
    # NoMethodError: private method `new' called for MyLogger:Class
    

提交回复
热议问题