简体   繁体   English

Minitest中的mc变量名称是什么意思?

[英]What does the mc variable name in Minitest mean?

In the minitest.rb file is inside the module Minitest the variable mc defined. minitest.rb文件中的模块Minitest包含定义的变量mc What is this variable doing? 这个变量在做什么? I can't derive it from the context. 我不能从上下文中得出它。

Here is a part of the code: 这是代码的一部分:

##
# :include: README.rdoc

module Minitest
  VERSION = "5.8.2" # :nodoc:
  ENCS = "".respond_to? :encoding # :nodoc:

  @@installed_at_exit ||= false
  @@after_run = []
  @extensions = []

  mc = (class << self; self; end)

Way back in the old days, before we had the Object#singleton_class method, the only way to get access to the singleton class was to open up the singleton class and return self from the class definition expression. 追溯到过去,在拥有Object#singleton_class方法之前,访问单例类的唯一方法是打开单例类并从类定义表达式返回self

Remember, a class definition expression, like all other definition expressions, evaluates to the value of the last expression evaluated inside the definition, eg: 请记住,与所有其他定义表达式一样,类定义表达式的计算结果是定义内最后计算的表达式的值,例如:

class Foo
  42
end
# => 42

Remember also that inside a class definition expression, the value of the special variable self is the class object itself: 还请记住,在类定义表达式中,特殊变量self的值是类对象本身:

class Bar
  self
end
# => Bar

And last but not least, remember that class << some_expression opens up the singleton class of whatever object some_expression evaluates to. 最后但并非最不重要的一点,请记住, class << some_expression打开了some_expression求值对象的单例类。

Putting it all together: 放在一起:

class << self # Here, self is Minitest
  self        # Here, self is the singleton class of Minitest
end

Opens up the singleton class of self , which is the Minitest module itself, then it returns self from the singleton class definition, which is the class itself, ergo the singleton class of Minitest . 打开self的单例类,即Minitest模块本身,然后从singleton类定义(即类本身)返回self ,从而对Minitest的单例类进行操作。

As to why the variable is named mc : that's short for "metaclass", which is one of the few dozen names that were proposed for what we now call the singleton class . 至于为什么将变量命名为mc :这是“元类”的缩写,它是为我们现在称为单例类提议的几十个名称之一。 ( Some of the other suggestions were eigenclass (my personal favorite), shadow class, virtual class (yuck!), ghost class, own class, … ) It's a bit of an unfortunate name, because the term metaclass has a well-defined meaning that does not fully match what a singleton class is in Ruby. 其他一些建议是本征类(我个人最喜欢的),影子类,虚拟类(糟糕!),鬼类,自己的类…… )。这有点不幸,因为元类一词的含义很明确与Ruby中的单例类完全不匹配。

Nowadays, we would probably just call singleton_class directly, or, if we want to cache it for performance reasons, do something like 如今,我们可能会直接调用singleton_class ,或者,如果出于性能原因要对其进行缓存,请执行以下操作

sc = singleton_class

instead. 代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM