今天花了點時間試著了解 Ruby Class/Object 的內部實現:
以及 singleton class 的創建機制:
eval.c -> eval.c: rb_extend_object activate eval.c eval.c -> class.c: rb_singleton_class activate class.c class.c -> class.c: singleton_class_of activate class.c class.c -> class.c: rb_make_metaclass activate class.c class.c -> class.c: make_singleton_class activate class.c class.c -> class.c: rb_class_boot activate class.c class.c -> class.c: rb_class_alloc activate class.c deactivate class.c deactivate class.c class.c -> class.c: rb_singleton_class_attached activate class.c deactivate class.c deactivate class.c deactivate class.c deactivate class.c deactivate class.c class.c --> eval.c eval.c -> class.c: rb_include_module
借用 RHG 裡面的一張圖來說明 singleton class 跟 obj 及 original class 的關係:
從短短的 make_singleton_class 就可以看出 code 寫得很簡潔易懂,果然是裡外都很漂亮:
static inline VALUE
make_singleton_class(VALUE obj)
{
VALUE orig_class = RBASIC(obj)->klass;
VALUE klass = rb_class_boot(orig_class);
FL_SET(klass, FL_SINGLETON);
RBASIC(obj)->klass = klass;
rb_singleton_class_attached(klass, obj);
METACLASS_OF(klass) = METACLASS_OF(rb_class_real(orig_class));
return klass;
}
更詳細的 Ruby 內部實現介紹可以參考這兩份簡報: