2009-09-26 11 views
5

चलो कहते हैं कि मैं इस तरह एक सिंगलटन वर्ग करते हैंरूबी में एक सिंगलटन वर्ग के लिए सुविधा वर्ग पद्धतियां जोड़ने का तरीका

Settings.instance.timeout 

लेकिन मैं नहीं बल्कि कि

Settings.timeout 

एक स्पष्ट तरीका को यह काम करने के लिए छोटा था imple संशोधित करने के लिए किया जाएगा करने के लिए सेटिंग्स की मनोभाव:

class Settings 
    include Singleton 

    def self.timeout 
    instance.timeout 
    end 

    def timeout 
    # lazy-load timeout from config file, or whatever 
    end 
end 

काम करता है यही कारण है कि है, लेकिन यह नहीं बल्कि मैन्युअल रूप से प्रत्येक उदाहरण विधि के लिए एक वर्ग विधि को लिखने के लिए कठिन होगा। यह रूबी है, ऐसा करने के लिए एक चालाक-चालाक गतिशील तरीका होना चाहिए।

उत्तर

10

एक तरह से करने के लिए यह इस तरह है:

require 'singleton' 
class Settings 
    include Singleton 

    # All instance methods will be added as class methods 
    def self.method_added(name) 
    instance_eval %Q{ 
     def #{name} 
     instance.send '#{name}' 
     end 
    } 
    end 


    def timeout 
    # lazy-load timeout from config file, or whatever 
    end 
end 

Settings.instance.timeout 
Settings.timeout 

आप और अधिक ठीक बेहतर नियंत्रण है जिस पर तरीकों को सौंपने के लिए है, तो आप प्रतिनिधिमंडल तकनीक का उपयोग कर सकते हैं:

require 'singleton' 
require 'forwardable' 
class Settings 
    include Singleton 
    extend SingleForwardable 

    # More fine grained control on specifying what methods exactly 
    # to be class methods 
    def_delegators :instance,:timeout,:foo#, other methods 

    def timeout 
    # lazy-load timeout from config file, or whatever 
    end 

    def foo 
    # some other stuff 
    end 

end 

Settings.timeout 

Settings.foo 

दूसरी ओर तरफ, मैं मॉड्यूल का उपयोग करने की सलाह देता हूं यदि इच्छित कार्यक्षमता व्यवहार तक ही सीमित है, ऐसे समाधान होंगे:

module Settings 
    extend self 

    def timeout 
    # lazy-load timeout from config file, or whatever 
    end 

end 

Settings.timeout 
+1

बहुत बढ़िया जवाब। मेरे विशेष मामले में सिंगलफॉरवर्ड योग्य वही है जो मैं ढूंढ रहा था। धन्यवाद! –

संबंधित मुद्दे