Last active
March 12, 2019 13:05
-
-
Save christoph-daehne/72e56b5d76ef06884eb4 to your computer and use it in GitHub Desktop.
Groovy DSL example: Florist, 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
class BouquetConfiguration extends ArrayList<String> { | |
int howMany(String flower) { | |
return this.count { it == flower } | |
} | |
String toString() { | |
return "Bouquet: " + this.toString() | |
} | |
} | |
class FloristConfiguration { | |
final Map<String, BouquetConfiguration> catalog = [:] | |
String toString() { | |
return "Florist: " + catalog.toString() | |
} | |
} | |
class BouquetConfigurationDsl { | |
private final BouquetConfiguration bouquet | |
BouquetConfigurationDsl(BouquetConfiguration bouquet) { | |
this.bouquet = bouquet | |
} | |
void flower(String flower) { | |
bouquet << flower | |
} | |
} | |
class FloristConfigurationDsl { | |
private final FloristConfiguration florist | |
FloristConfigurationDsl(FloristConfiguration florist) { | |
this.florist = florist | |
} | |
BouquetConfiguration bouquet( | |
String name, | |
@DelegatesTo(strategy = Closure.DELEGATE_FIRST, value = BouquetConfigurationDsl) Closure script | |
) { | |
def bouquet = florist.catalog[name] | |
if (bouquet == null) { | |
bouquet = florist.catalog[name] = new BouquetConfiguration() | |
} | |
script.resolveStrategy = Closure.DELEGATE_FIRST | |
script.delegate = new BouquetConfigurationDsl(bouquet) | |
script() | |
return bouquet | |
} | |
} | |
class Florist { | |
static FloristConfiguration create( | |
@DelegatesTo(strategy = Closure.DELEGATE_FIRST, value = FloristConfigurationDsl) Closure script | |
) { | |
def florist = new FloristConfiguration() | |
script.resolveStrategy = Closure.DELEGATE_FIRST | |
script.delegate = new FloristConfigurationDsl(florist) | |
script() | |
return florist | |
} | |
} | |
def florist = Florist.create { | |
bouquet "meadow", { | |
flower "cornflower" | |
flower "cornflower" | |
flower "poppy" | |
flower "calendula" | |
} | |
bouquet "roses", { | |
flower "rose" | |
flower "rose" | |
flower "rose" | |
flower "rose" | |
} | |
// add another calendula to existing bouquet | |
bouquet "meadow", { | |
flower "calendula" | |
} | |
} | |
println florist |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment