Metaprogramming Class-Level Macros

If you’ve used Ruby for any time at all, you’re likely to have used attr_accessor, the method that defines reader and writer methods for instance variables:

 class​ Song
  attr_accessor ​:duration
 end

If you’ve written a Ruby on Rails application, you’ve probably used has_many:

 class​ Album < ActiveRecord::Base
  has_many ​:tracks
 end

These are both examples of class-level methods that generate code behind the scenes. Because of the way they expand into something bigger, folks sometimes call these kinds of methods macros.

Let’s create a trivial example and then build it up into something realistic. We’ll start by implementing a simple method that adds logging capabilities to instances of a class. ...

Get Programming Ruby 3.3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.