Prev | Current Page 31 | Next

Brad Ediger

"Advanced Rails"


Putting this together, we can open up the Object class and add an instance method to
every object that returns that object??™s singleton class:
class Object
def metaclass
class <self
end
end
end
This method forms the basis of Metaid, which is described shortly.
Method missing
After all of that confusion, method_missing is remarkably simple. There is one rule: if
the whole method lookup procedure fails all the way up to Object, method lookup
is tried again, looking for a method_missing method rather than the original method.
If the method is found, it is called with the same arguments as the original method, with
the method name prepended. Any block given is also passed through.
The default method_missing function in Object (rb_method_missing) raises an exception.
Metaid
why the lucky stiff has created a tiny library for Ruby metaprogramming called
metaid.rb. This snippet is useful enough to include in any project in which metaprogramming
is needed:*
* ???Seeing Metaclasses Clearly.??? http://whytheluckystiff.net/articles/seeingMetaclassesClearly.html
18 | Chapter 1: Foundational Techniques
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
This library defines four methods on every object:
metaclass
Refers to the singleton class of the receiver (self).


Pages:
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43