Meta Programming Meta
Meta programming is one of the most difficult, but rewarding styles of programming I have ever tried. It comes as second to nature to a language like ruby, but to me, it requires an incredible amount of mental strength to accomplish some of the simplest tasks. My first non-tutorial attempt was for a rails plugin auto_html. I added some of the easiest meta programming one can do; write out new methods as strings and have them transformed into regular methods. From auto_html_for.rb:
suffixed = raw_attr.to_s + AutoHtmlFor.options[:htmlized_attribute_suffix]
setter = %|
def #{suffixed}=(val)
@#{suffixed} = val
end
|
getter = %|
def #{suffixed}
if @#{suffixed}.nil?
self.auto_html_prepare
end
@#{suffixed}
end
|
class_eval getter
class_eval setter
Everything between %| and | is one string, and then class_eval evaluates that string and adds a new method to the class it is working in. Now that it is all finished, it looks so simple, but it took some effort to get right. What got accomplished with this code block though, is remarkably powerful, but only the tip of the iceberg when it comes to meta programming.
If you need to flex some serious brain muscle, start up irb and start getting meta.
4/09