Metaprogramming – A Deep Dive
We introduced metaprogramming in the previous chapter and defined it as code that generates code. Ruby has numerous powerful methods that make it possible to allow code that writes code. Furthermore, metaprogramming is most often used to create flexible interfaces. This is especially useful when you create Ruby gems that are pluggable Ruby libraries in other Ruby programs. Metaprogramming is also used in creating Ruby-based frameworks, such as Sinatra, Ruby on Rails, or when you create your own framework. Ruby on Rails, the most popular Ruby framework, is loaded with metaprogramming magic.
In the previous chapter, we stated that metaprogramming makes use of multiple elements available within the Ruby language. We discussed three such elements: blocks, procs, and lambdas. In this section, we will take a practical approach in order to understand metaprogramming and discuss topics such as opening classes in Ruby, monkey patching, and some in-built...