Method Interception and DSLs

We can implement the DSL for ordering pizza without really using a PizzaShop class. We can do that by purely intercepting method calls. Let’s start with the code to order pizza (stored in a file named orderPizza.dsl):

CreatingDSLs/orderPizza.dsl
 
size large
 
crust thin
 
topping Olives, Onions, Bell_Pepper
 
address "101 Main St., ..."
 
card visa, '1234-1234-1234-1234'

It hardly looks like code. It looks more like a data file. However, that’s pure Groovy code, and we’re going to execute it (everything we see in that file, except the strings in double quotes, is either method names or variable names). But before that, we have to perform a few tricks…er, I mean design our DSL.

Let’s create a file named GroovyPizzaDSL.groovy ...

Get Programming Groovy 2 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.