Ruby 在父模块中访问模块内变量的正确方法
比如说,我有以下情况:Ruby 在父模块中访问模块内变量的正确方法,ruby,module,Ruby,Module,比如说,我有以下情况: module A module B def self.make @correlation_id ||= SecureRandom.uuid end end end 现在,对于外部世界,我只希望他们能够通过模块A访问correlation_id: A.correlation\u id。如何从模块A访问@correlation\u id 我做了以下几件事,效果不错,但有一个我不想要的副作用 module A module B
module A
module B
def self.make
@correlation_id ||= SecureRandom.uuid
end
end
end
现在,对于外部世界,我只希望他们能够通过模块A访问correlation_id:
A.correlation\u id
。如何从模块A访问@correlation\u id
我做了以下几件事,效果不错,但有一个我不想要的副作用
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::B.make
之后,我可以做A.correlation\u id
,但遗憾的是,我也能做A::B.correlation\u id
。我如何缓解这个问题
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\u id”
这似乎有点过分。我肯定会这么做,但有没有更标准的方法?奇怪的是:)您尝试的一开始就不是标准的(允许A
访问A::B
的类实例变量而不允许A::B
这样做是违反OOP的),所以没有标准的方法。为什么.freeze
会使这更有效?因为字符串只会在解析时创建并重用。这是最近推出的一项功能。