【问题标题】:Where are mixins implemented in Rubinius?Rubinius 在哪里实现了 mixin?
【发布时间】:2011-10-08 07:33:58
【问题描述】:

Rubinius 源代码中负责包含模块的代码在哪里?(具体而言,将模块放置为对象类的超类。)

【问题讨论】:

  • 恐怕是放在vm/builtin/*里,是cpp写的。
  • 你低估了鲁比尼乌斯的酷 :-)

标签: ruby rubinius


【解决方案1】:

如果您查看Module#include 的文档,您会发现它委托给Module#append_features

在每个参数上以相反的顺序调用Module.append_features

Module#append_features 的文档反过来(非常简要地)描述了默认 Ruby 混合算法的工作原理:

当这个模块包含在另一个模块中时,Ruby 在这个模块中调用append_features,并将mod 中的接收模块传递给它。 Ruby 的默认实现是将此模块的常量、方法和模块变量添加到 mod,如果此模块尚未添加到 mod 或其祖先之一。另见Module#include

如果您查看Rubinius sourcecode 中的Module#append_features,您会发现它是Module#include_into 的别名:

# Called when this Module is being included in another Module.
# This may be overridden for custom behaviour. The default
# is to add constants, instance methods and module variables
# of this Module and all Modules that this one includes to +klass+.
#
# See also #include.
#
alias_method :append_features, :include_into

所以,最后,Module#include_into 是真正的交易:

# Add all constants, instance methods and module variables
# of this Module and all Modules that this one includes to +klass+
#
# This method is aliased as append_features as the default implementation
# for that method. Kernel#extend calls this method directly through
# Module#extend_object, because Kernel#extend should not use append_features.
def include_into(klass)
  ...

您的具体问题:

正好将模块作为对象类的超类

this loop回复:

k = klass.direct_superclass
while k
  if k.kind_of? Rubinius::IncludedModule
    # Oh, we found it.
    if k == mod
      # ok, if we're still within the directly included modules
      # of klass, then put future things after mod, not at the
      # beginning.
      insert_at = k unless superclass_seen
      add = false
      break
    end
  else
    superclass_seen = true
  end

  k = k.direct_superclass
end

关注insert_at

【讨论】:

    猜你喜欢
    • 2011-06-07
    • 1970-01-01
    • 2012-04-13
    • 1970-01-01
    • 2010-10-11
    • 2019-10-14
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多