Ruby:C 类包含模块 M;在 M 中包含模块 N 不会影响 C。什么给出?

2024-04-19

更详细地说,我有一个模块Narf,它为一系列类提供了基本功能。具体来说,我想影响所有继承的类Enumerable. So I include Narf in Enumerable.

Array是一个类,其中包括Enumerable默认情况下。然而,它并没有受到后期纳入的影响Narf在模块中。

有趣的是,包含后定义的类得到Narf from Enumerable.

Example:

# 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 而不是其自己的模块。这实际上可能没问题并且会起作用。这是我推荐的方法,尽管它也不完美。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Ruby:C 类包含模块 M;在 M 中包含模块 N 不会影响 C。什么给出? 的相关文章

随机推荐