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

前端 未结 5 2012
悲&欢浪女
悲&欢浪女 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 04:05

    Here is an alternative that does not really fall under the scope of my first answer. You can create a mixin module that undefines all the methods of the base class and then uses the method_missing technique:

    module SingletonRedirect
      def included(base_class)
        instance = base_class.instance
        base_class.class_eval do
          methods.each &undef_method
    
          define_method :method_missing do |name, *arguments|
            instance.public_send name, *arguments
          end
        end
      end
    end
    

    To implement the idea, instance is a local variable that is passed via closure to the blocks in the calls to Class#class_eval and Module#define_method. Then, we do not need to refer to it by base_class.instance, so we can clear out all the methods, including that one (a technique known as a blank slate). Then, we define a method redirection system that takes advantage of the flat scope to refer to instance as a variable and call only methods that are publicly available via Object#public_send.

提交回复
热议问题