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

时间:2015-11-17 10:35:26

标签: ruby metaprogramming minitest

在minitest.rb文件中,模块Minitest内定义了变量mc。这个变量在做什么?我不能从上下文中得出它。

以下是代码的一部分:

##
# :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)

1 个答案:

答案 0 :(得分:1)

回到过去,在我们使用Object#singleton_class方法之前,访问单例类的唯一方法是打开单例类并从类定义表达式返回self

请记住,类定义表达式与所有其他定义表达式一样,计算定义中定义的最后一个表达式的值,例如:

class Foo
  42
end
# => 42

还要记住,在类定义表达式中,特殊变量self的值是类对象本身:

class Bar
  self
end
# => Bar

最后但并非最不重要的是,请记住class << some_expression打开了some_expression评估的任何对象的单例类。

全部放在一起:

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

打开self的单例类,它是Minitest模块本身,然后从单例类定义返回self,这是类本身,ergo是单例类Minitest

至于为什么该变量被命名为mc:这是&#34;元类&#34;的缩写,这是我们现在称之为< em>单身类。 (Some of the other suggestions were eigenclass (my personal favorite), shadow class, virtual class (yuck!), ghost class, own class, …)这是一个不幸的名字,因为the term metaclass has a well-defined meaning与Ruby中的单例类不完全匹配。

如今,我们可能只是直接调用singleton_class,或者,如果我们出于性能原因要缓存它,请执行类似

的操作
sc = singleton_class

代替。