ExpandoMetaClass and DSLs

Categories apply only within the use blocks, and their effect is fairly limited in scope. If we want the method injection to be effective throughout our application, we can use the ExpandoMetaClass instead of categories. Let’s use the ExpandoMetaClass to implement the DSL syntax we saw in the previous section:

getDays = { ->
getAgo = { ->
def​ date = ​Calendar​.instance
date.add(​Calendar​.DAY_OF_MONTH, -delegate)
Calendar​.metaClass.at = { ​Map​ time ->
def​ hour = 0
def​ minute = 0
time.each {key, value ->
hour = key.toInteger()
minute = value.toInteger()
delegate.set(​Calendar​.HOUR_OF_DAY, ...

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.