Categories and DSLs

Using categories, we can intercept method calls in a controlled fashion (see Injecting Methods Using Categories). We can put that to use in creating a DSL. Let’s figure out ways to implement the following fluent call: 2.days.ago.at(4.30).

2 is an instance of Integer, and we know that days is not a property on it. We’ll inject that, using categories, as a property (the getDays method). The days is just noise here, but in another context it may be useful to differentiate between five days ago and five minutes ago. It provides connectivity in the sentence “two days ago at 4.30.” We can implement the method getDays that accepts Integer and returns the received instance. In the getAgo method (for the ago property), we accept ...

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.