Metaprogramming is programming about programming: it's code that writes code, but in a different way than compile-time generation like most
Java code generation. Because Ruby is highly dynamic, things like getters and setters can be written by a method that writes additional methods:
This ends up generating a class that looks like this:
A trivial example, yes, but it's important to understand when and how this is happening. This allows very simple programmatic generation of instance methods *at runtime*. Now think about something like this:
Now, with an absolute minimum of intrusiveness, we've defined some instance requirements, at runtime, in code, using a mini-validation DSL.
validates_presence_of and
validates_length_of are methods that generate behavior.
One thing I worked on was a
test framework for web pages. Driving Selenium, I was able to code and test pages like this:
Like Lisp macros, metaprogramming can be difficult to explain, but the power and clarity it can provide is *huge*.