的情况下调用Ruby

的情况下调用Ruby

本文介绍了在没有引用"instance"的情况下调用Ruby Singleton的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不引用其实例的情况下调用Singleton Object的方法

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

SingletonKlass.my_method

代替

SingletonKlass.instance.my_method

我想出了这个解决方案(在类中使用method_missing):

i've came up with this solution (using method_missing in the class):

require 'singleton'

class SingletonKlass
  include Singleton

  def self.method_missing(method, *args, &block)
    self.instance.send(method, *args)
  end

  def my_method
     puts "hi there!!"
  end
end

这有什么缺点吗?有没有更好的解决方案?您有什么建议吗?

is there any drawback to this ?is there any better solution ?any recommendation from you ?

谢谢.

更新:

我的目标是让一个模块与单例类混合使用:

my aim is to have a module to be mixed-in with singleton classes:

module NoInstanceSingleton
   def method_missing(method, *args)
      self.instance.send(method, *args)
   end
end

end然后在类中使用它:

end then use it in the class:

class SingletonKlass
   include Singleton
   extend NoInstanceSingleton

  def method1; end
  def method2; end
  ...
  def methodN; end
end

我希望能够直接致电:

SingletonKlass.method1

推荐答案

使用可转发和def_delegators:

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

编辑:如果要包括自己定义的所有方法,可以这样做

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

这篇关于在没有引用"instance"的情况下调用Ruby Singleton的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 07:06