Skip to content

Instantly share code, notes, and snippets.

@christoph-daehne
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christoph-daehne/96ad31d3802c68316f6a to your computer and use it in GitHub Desktop.
Save christoph-daehne/96ad31d3802c68316f6a to your computer and use it in GitHub Desktop.
Groovy DSL example: Bouquet
// our configuration model
class BouquetConfiguration {
private final List<String> flowers = []
// method for use at runtime
int howMany(String flower) {
return flowers.count { it == flower }
}
// DSL keyword for use at DSL execution
void flower(String flower) {
flowers << flower
}
String toString() {
return "Bouquet: " + flowers.toString()
}
}
class Bouquet {
static BouquetConfiguration create(
@DelegatesTo(strategy = Closure.DELEGATE_FIRST, value = BouquetConfiguration) Closure script
) {
def bouquet = new BouquetConfiguration()
script.resolveStrategy = Closure.DELEGATE_FIRST
script.delegate = bouquet
script()
return bouquet
}
}
def bouquet = Bouquet.create {
flower "cornflower"
flower "cornflower"
flower "poppy"
flower "calendula"
}
println bouquet
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment