Last active
March 12, 2019 13:04
-
-
Save christoph-daehne/ba5743e3629ec04dc098 to your computer and use it in GitHub Desktop.
Groovy DSL example: Better Bouquet, see https://sandstorm.de/de/blog/post/how-to-create-a-dsl-with-groovy.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// our configuration model | |
class BouquetConfiguration extends ArrayList<String> { | |
int howMany(String flower) { | |
return this.count { it == flower } | |
} | |
String toString() { | |
return "Bouquet: " + this.toString() | |
} | |
} | |
// our DSL keyword | |
class BouquetConfigurationDsl { | |
private final BouquetConfiguration bouquet | |
BouquetConfigurationDsl(BouquetConfiguration bouquet) { | |
this.bouquet = bouquet | |
} | |
void flower(String flower) { | |
bouquet << flower | |
} | |
} | |
class Bouquet { | |
static BouquetConfiguration create( | |
@DelegatesTo(strategy = Closure.DELEGATE_FIRST, value = BouquetConfigurationDsl) Closure script | |
) { | |
def bouquet = new BouquetConfiguration() | |
script.resolveStrategy = Closure.DELEGATE_FIRST | |
script.delegate = new BouquetConfigurationDsl(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