CSC/ECE 517 Fall 2007/wiki1b 4 19

From Expertiza_Wiki
Revision as of 23:10, 1 October 2007 by Rrsahgal (talk | contribs)
Jump to navigation Jump to search

Metaprogramming in Ruby

Introduction to metaprogramming

Metaprogramming,just as the name suggests, means “Programming a program”. This means that one can define classes and methods at runtime. It is possible only because of the dynamic nature of the language.

For an excellent introduction to metaprogramming please visit [1]


Under the hood

So you think how does ruby achieve this great feat. Well its not rocket science. Every object in ruby has a associated class that is accessible to only that object. Now recall that everything in ruby is an object. Put two and two together and you realize that classes and modules are also objects and so they too have classes, all for themselves.

These classes are called Singleton classes(accessible to only a single object). So when you send a message to an object, its singleton class is first checked to see if it has methods defined that can handle this message.

Metaprogramming is made possible because of singleton classes. Whenever we dynamically define a method on an object, it is added as a method of the singleton class for this object.

For an excellent discussion about singleton classes and their properties, [2] is a must read.

Guide

So one might think, well I can write code that will generate code, what good can that do. Well then you must read further.

There is an excellent blog entry on the classification of metaprogramming into different types (based on usability) I dont think I could do a better job of explaining metaprogramming in ruby concisely. Thus, I refer you to [3]

To help you along the way, here is some information 1.DSL stands for domain specific language(for point 2) 2.Point 4 gives some more uses of method missing besides the roman numeral example, we went through. 3.Point 6 is similar to the wrapping scenario discussed in class.

Some other useful links

A presentation made at a conference [4]

About Metaclasses [5]