Seeing Metaclasses Clearly #
If you’re new to metaprogramming in Ruby and you’d like to start nursing a deep understanding for it, I’ve written a detailed article dissecting metaclasses. It’s all based on the following code, which I call Metaid.
class Object # The hidden singleton lurks behind everyone def metaclass; class << self; self; end; end def meta_eval &blk; metaclass.instance_eval &blk; end # Adds methods to a metaclass def meta_def name, &blk meta_eval { define_method name, &blk } end # Defines an instance method within a class def class_def name, &blk class_eval { define_method name, &blk } end end
The article contains a lot of stuff I excluded from chapter six of my cartoon Ruby book because it was just getting too specific for the common reader.
Update: Thanks to feedback from Ruby-Talk and sundry readers out there, the article is proofread and errors are being fixed. Certainly post here in the comments if you have further.
MenTaLguY
Awesome. This is what I was reaching for with my earlier Dwemthy’s array hackery, but I just didn’t have the vision.
I’d be very happy if metaid became part of the ruby core in some fashion.
(Pedant that I am, I’d prefer the more verbose and consistent singleton_class, singleton_class_eval, define_singleton_method, and define_class_method in place of metaclass, meta_eval, meta_def, and class_def. But I cannot speak for others.)
why
I may change the names. It’s confusing to people who read the article and then read class.c. But I hate to use a name other than metaclass because I like it so.
MenTaLguY
I think Matz’s choice of singleton class is more suggestive of what’s actually going on—these are the grubby one-off classes depending from the bottom of the class hierarchy, rather than those “meta” classes hovering above it all, transcendant-like.
I wish that weren’t the case, because metaclass is so mellifluous, whereas singleton class is so not.
daigo
Excellent! This entry should be prized MVP of the first half of the year.
Daniel Berger
I never meta class I didn’t like.
Comments are closed for this entry.