更详细地说,我有一个模块 Narf
,它为一系列类提供基本功能。具体来说,我想影响所有继承 Enumerable
的类。所以我在 Enumerable
中 include Narf
。
Array
是默认包含 Enumerable
的类。然而,它不受 Narf
延迟包含在模块中的影响。
有趣的是,在包含之后定义的类从 Enumerable
获取 Narf
。
示例:
# This module provides essential features
module Narf
def narf?
puts "(from #{self.class}) ZORT!"
end
end
# I want all Enumerables to be able to Narf
module Enumerable
include Narf
end
# Fjord is an Enumerable defined *after* including Narf in Enumerable
class Fjord
include Enumerable
end
p Enumerable.ancestors # Notice that Narf *is* there
p Fjord.ancestors # Notice that Narf *is* here too
p Array.ancestors # But, grr, not here
# => [Enumerable, Narf]
# => [Fjord, Enumerable, Narf, Object, Kernel]
# => [Array, Enumerable, Object, Kernel]
Fjord.new.narf? # And this will print fine
Array.new.narf? # And this one will raise
# => (from Fjord) ZORT!
# => NoMethodError: undefined method `narf?' for []:Array
最佳答案
我想到了两个可以解决您的问题的方法。他们都不是很漂亮:
a) 遍历所有包含 Enumerable 的类,并使它们也包含 Narf。像这样:
ObjectSpace.each(Module) do |m|
m.send(:include, Narf) if m < Enumerable
end
虽然这很骇人听闻。
b) 直接将功能添加到 Enumerable 而不是它自己的模块。这实际上可能没问题,并且会起作用。这是我推荐的方法,尽管它也不完美。
关于Ruby:C类包含模块M;在 M 中包含模块 N 不会影响 C。什么给了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1655623/