One Final Lesson - Metaprogramming in Rails - Metaprogramming Ruby 2: Program Like the Ruby Pros (2014)

Metaprogramming Ruby 2: Program Like the Ruby Pros (2014)

Part 2. Metaprogramming in Rails

Chapter 13. One Final Lesson

We’ve been together on a daring adventure, starting with the very basics of metaprogramming and closing with a tour of the Rails source code. Before we part, there is one last insight that I will share—possibly the most important of them all.

Metaprogramming Is Just Programming

When I started learning metaprogramming, it looked like magic. I felt like leaving my usual programming behind to enter a new world—a world that was surprising, exciting, and sometimes a bit scary.

As I finish revising this book, the feeling of magic is still there. However, I realize now that in practice there is no hard line separating metaprogramming from plain old vanilla programming. Metaprogramming is just another powerful set of coding tools that you can wield to write code that’s simple, clean, and well tested.

I’ll go out on a limb to make a bolder assertion: with Ruby, the distinction between metaprogramming and regular code is fuzzy—and ultimately pointless. Once you have an in-depth understanding of the language, you’ll have a hard time deciding which techniques and idioms are “meta” and which ones are plain old programming.

In fact, metaprogramming is so deeply ingrained in Ruby that you can barely write an idiomatic Ruby program without using a few metaprogramming spells. The language actually expects that you’ll tweak the object model, reopen classes, define methods dynamically, and manage scopes with blocks. As Bill might say in a Zen moment, “There is no such thing as metaprogramming. It’s just programming all the way down.”