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
。我将如何缓解这个问题?
这似乎有点元。我一定会这样做,但有没有更标准的方法?只是好奇:) – David
你试图在第一位不是标准的(允许'A'访问'A :: B'的类实例变量而不允许'A :: B'这样做是违反OOP的),所以没有标准的方法。 – sawa
为什么'.freeze'使这个效率更高? – David