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


i call method of singleton object without reference instance

singletonklass.my_method 

instead of

singletonklass.instance.my_method 

i've came solution (using method_missing in 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 drawback ? there better solution ? recommendation ?

thank you.

update:

my aim have module mixed-in singleton classes:

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

end use in class:

class singletonklass    include singleton    extend noinstancesingleton    def method1; end   def method2; end   ...   def methodn; end end 

i want able directly call:

singletonklass.method1 

using forwardable , 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 want include methods you've defined yourself, 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 

Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -