2014-07-18 181 views
0

比方說,比如我有以下情況:有道模塊內訪問變量,而在父模塊

module A 
    module B 

    def self.make 
     @correlation_id ||= SecureRandom.uuid 
    end 

    end 
end 

現在,對於外面的世界,我只希望他們能夠訪問CORRELATION_ID通過模塊A:

A.correlation_id。我將如何從模塊A訪問@correlation_id

我做了以下,它的工作,但有一個副作用,我不想要。我做A::B.make

module A 
    module B 

    def self.make 
     @correlation_id ||= SecureRandom.uuid 
    end 

    private 

    def self.correlation_id 
     @correlation_id 
    end 
    end 

    def self.correlation_id 
    A::B.correlation_id 
    end 
end 

有了到位後,我可以做A.correlation_id,但可悲的是,我也能做到A::B.correlation_id。我將如何緩解這個問題?

回答

1
module A 
    module B 
    def self.make 
     @correlation_id ||= SecureRandom.uuid 
    end 
    end 
    def self.correlation_id 
    B.instance_variable_get("@correlation_id") 
    end 
end 

爲了提高效率,把.freeze"@correlation_id"後。

+0

這似乎有點元。我一定會這樣做,但有沒有更標準的方法?只是好奇:) – David

+0

你試圖在第一位不是標準的(允許'A'訪問'A :: B'的類實例變量而不允許'A :: B'這樣做是違反OOP的),所以沒有標準的方法。 – sawa

+0

爲什麼'.freeze'使這個效率更高? – David