gpt4 book ai didi

ruby - 从深层嵌套模块访问常量

转载 作者:数据小太阳 更新时间:2023-10-29 08:47:49 24 4
gpt4 key购买 nike

我有以下模块结构:

-->Analytics (module)
--> Reporting
--> Metrics
--> Computed

-->Content (class)

Computed 中,我有一些模块常量 FOOContent 中有许多方法可以深入到 Computed 并访问 FOO。目前,这样做的方式是:

#content.rb
...
def do_something
...
foo = Analytics::Reporting::Metrics::Computed::FOO
...
end

访问深层嵌套模块常量或变量的最佳实践是什么?我不能以任何不同的方式命名 Content。有更好的方法吗?

最佳答案

Content 的类主体中,执行以下操作:

include Analytics::Reporting::Metrics::Computed

然后,您将可以在没有显式命名空间的情况下访问 FOO

module A
module B
module C
module D
FOO = "This is FOO from A::B::C::D"
end
end
end
end

class E
include A::B::C::D
p FOO
end
# => "This is FOO from A::B::C::D"

关于ruby - 从深层嵌套模块访问常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22178190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com