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

标签 ruby module

更详细地说,我有一个模块 Narf,它为一系列类提供基本功能。具体来说,我想影响所有继承 Enumerable 的类。所以我在 Enumerableinclude 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/

相关文章:

ruby-on-rails - 我应该使用 Redis 哈希还是 Ruby 哈希?

java - 绕过 Android 模块的循环依赖?

ruby-on-rails - Rspec:在模型无效时显示模型的错误

ruby - 没有路由匹配 Controller

python - 关于在我的计算机上存储第三方模块的建议

java - 如何创建多 war war 模块?

asp.net - 使用管理面板编辑网站的 DotNetNuke 皮肤 CSS

java - "package"和 "module"有什么区别?

ruby-on-rails - 当使用 attr_encrypted 进行 activerecord 存储时,我得到 nil 和 Empty

ruby - Perl - Ruby 映射?