Calling a method of a Ruby Singleton without the reference of 'instance'

前端 未结 5 2023
悲&欢浪女
悲&欢浪女 2021-01-21 03:37

I would like to call a method of a Singleton Object without the reference to its instance

SingletonKlass.my_method

instead of

S         


        
5条回答
  •  余生分开走
    2021-01-21 03:53

    Using forwardable and def_delegators:

    require 'singleton'    
    require 'forwardable'
    
    class SingletonKlass
      include Singleton
      class << self
        extend Forwardable
        def_delegators :instance, :my_method
      end
    
      def my_method
         puts "hi there!!"
      end
    end
    
    SingletonKlass.my_method
    

    Edit: If you want to include all the methods you've defined yourself, you could do

    require 'singleton'    
    require 'forwardable'
    
    class SingletonKlass
      include Singleton
    
      def my_method
         puts "hi there!!"
      end
    
      class << self
        extend Forwardable
        def_delegators :instance, *SingletonKlass.instance_methods(false)
      end
    end
    
    SingletonKlass.my_method
    

提交回复
热议问题