DRY Your Code with Macros

Crystal’s original inspiration, Ruby, is a master of runtime introspection and manipulation of code—also called metaprogramming. Metaprogramming is the secret to Ruby on Rails’ sophistication, but Ruby has no macros. Crystal is a compiled language, so it doesn’t have an eval method to create new code in runtime. It has to take a different path, a competent system of macros to build code at compile time, and that will go a long way.

When you’re writing code, sometimes you’ll find yourself writing methods that are near duplicates of each other, only differing in name or parameters. In these cases, it might help if you could generate all this code automatically using one macro version of the method.

A macro is a function ...

Get Programming Crystal 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.