gpt4 book ai didi

ruby - 直接和通过 include 定义嵌套类

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

假设我正在为我的家庭存储系统建模。我有很多不同类型的 Container,我发现其中很多都有装饰品,因此我为这种常见情况设置了一些帮助程序代码。

我的容器中有我的Manplepiece 和我的Bookcase。我只在前者上存放装饰品;而后者拥有所有的装饰品,精装书和软装书。

这是一个初步的尝试:

module Properties
def has_ornament
include OrnamentThings
end

module OrnamentThings
module Things
class Ornament
end
end
end
end

class Container
extend Properties
end

class Mantlepiece < Container
has_ornament
end

class Bookcase < Container
has_ornament

module Things
class Hardback
end

class Paperback
end
end
end

[Mantlepiece, Bookcase].each do |place|
puts place.name
puts place.constants.inspect
puts place::Things.constants.inspect
end

# Output:
# Mantlepiece
# [:Things]
# [:Ornament]
# Bookcase
# [:Things]
# [:Hardback, :Paperback]

您可以看到 Mantlepiece 正确地嵌套了 Mantlepiece::Things::Ornament;但是 BookcaseThings 的类内声明意味着 Bookcase::Things 只嵌套 Hardback平装本Bookcase::Things::Ornament 丢失。

我能不能把这个写得简洁一点,这样 Bookcase 就可以调用 has_ornament,然后声明它自己的一组 Things,并把它们全部嵌套起来在同一个命名空间?

最佳答案

即使您的壁炉架和书柜都有东西,但这些东西是不同的(因为它们包含不同的类别)。所以他们不能只包含一些通用的 Things 模块;他们必须定义自己单独的 Things,就像您在 Bookcase 中通过声明 module Things 所做的那样。

def has_ornament
const_set(:Things, Module.new) unless const_defined? :Things, false
self::Things.include OrnamentThings
end

module OrnamentThings
class Ornament
end
end

之所以可行,是因为 Ruby 允许您使用与声明模块相同的语法重新打开模块。 has_ornament 定义了一个全新的 Things 模块,您可以打开它添加更多东西。如果您在自定义事物之后调用 has_ornament,它会跳过创建并添加到制作的模块中(false 确保我们正在查找Things 仅在当前类中)。

关于ruby - 直接和通过 include 定义嵌套类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49262382/

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