gpt4 book ai didi

ruby - 如何在嵌套子模块中自动包含模块

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

我有一个模块 Top,它有模块 AB。在它们中的每一个中,我都想使用模块 C 的类方法。为此,我必须为每个模块 AB 包含 C。是否可以在 Top 中包含 C 以便所有子模块都可以访问其类方法?

例子:

# I'll extend module C in example to make it shorter

module C
def foo; puts 'Foo!' end
end

module Top
extend C

module A end
module B end
end

# That's how it works now

Top.foo
#=> "Foo!"
Top::A.foo
#=> NoMethodError: undefined method `foo' for Top::A:Module
Top::B.foo
#=> NoMethodError: undefined method `foo' for Top::B:Module

# That's how I want it to work

Top.foo
#=> "Foo!"
Top::A.foo
#=> "Foo!"
Top::B.foo
#=> "Foo!"

最佳答案

其实是可以的
OP 更新了代码,所以这是我的实现:

class Module
def submodules
constants.collect {|const_name| const_get(const_name)}.select {|const| const.class == Module}
end
end


module C
# this gets called when the module extends another class or module
# luckily it does _not_ get called when we extend via :send
def self.extended(base)
# collect all submodules and extend them with self
base.submodules.each{|m| m.send :extend, self }
end
def c1
puts "c1"
end
end

module Top
module A;end
module B;end
# extend needs to go at the end - otherwise Top doesnt know about its submodules
extend C
end

Top.c1 # => "c1"
Top::A.c1 # => "c1"
Top::B.c1 # => "c1"

关于ruby - 如何在嵌套子模块中自动包含模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13947676/

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