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

前端 未结 5 2024
悲&欢浪女
悲&欢浪女 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-21 03:50

    The problem with your method_missing solution is that it will only redirect calls to instance if there does not exist a method of that name on SingletonKlass, which will cause problems if people want to access, for example, instance.__id__ through this interface you provide. There is not much of a problem with accessing SingletonKlass.instance the normal way, but if you really want to make a shortcut, the safest would be a constant:

    KlassInstance = SingletonKlass.instance
    

    If you want to define the constant dynamically, use Module#const_set:

    const_set :KlassInstance, SingletonKlass.instance
    

    You can extend upon this, too. For example, you can create a method that will create constants like this for you:

    def singleton_constant(singleton_class)
      const_set singleton_class.name, singleton_class.instance
    end
    

    Of course, because Module#const_set is a method of a module, this specific technique can only be performed in the context of a module or class. Another possibility is by a mixin module with an overloaded hook method:

    module SingletonInstance
      def included(base_class)
        const_set base_class.name, base_class.instance
        super
      end
    end
    

提交回复
热议问题