Prev | Current Page 48 | Next

Brad Ediger

"Advanced Rails"

Far more often, these techniques can be
used at a console prompt to find methods available on an object??”it??™s usually
quicker than reaching for a reference book:
Array.instance_methods.grep /sort/ # => ["sort!", "sort", "sort_by"]
ObjectSpace
ObjectSpace is a module used to interact with Ruby??™s object system. It has a few useful
module methods that can make low-level hacking easier:
??? Garbage-collection methods: define_finalizer (sets up a callback to be called
just before an object is destroyed), undefine_finalizer (removes those callbacks),
and garbage_collect (starts garbage collection).
??? _id2ref converts an object??™s ID to a reference to that Ruby object.
??? each_object iterates through all objects (or all objects of a certain class) and
yields them to a block.
30 | Chapter 1: Foundational Techniques
As always, with great power comes great responsibility. Although these methods can
be useful, they can also be dangerous. Use them judiciously.
An example of the proper use of ObjectSpace is found in Ruby??™s Test::Unit framework.
This code uses ObjectSpace.each_object to enumerate all classes in existence
that inherit from Test::Unit::TestCase:
test_classes = []
ObjectSpace.each_object(Class) {
| klass |
test_classes << klass if (Test::Unit::TestCase > klass)
}
ObjectSpace, unfortunately, greatly complicates some Ruby virtual machines. In particular,
JRuby performance suffers tremendously when ObjectSpace is enabled,
because the Ruby interpreter cannot directly examine the JVM??™s heap for extant
objects.


Pages:
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60