This post originated from an RSS feed registered with Ruby Buzz
by Red Handed.
Original Post: Seeing Metaclasses Clearly
Feed Title: RedHanded
Feed URL: http://redhanded.hobix.com/index.xml
Feed Description: sneaking Ruby through the system
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
# In class definitions, methods are added to the metaclass
# of the class being defined.
def meta_def name, &blk
metaclass.instance_eval { define_method name, &blk }
end
# Just defines a class method
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.