Created
September 3, 2010 15:01
-
-
Save tyama/563992 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// ================= DSL ================= | |
// カタコトな日本語だね。 | |
わいは 茶 に 砂糖 | |
あたいは、 茶 に 砂糖 と ミルク | |
おいらは 珈琲 に 砂糖, ミルク と リキュール | |
// ======================================= | |
"""注文内容:\n${allBreaks.collect { " - $it" }.join('\n')}""" | |
// out beverages and ingredients | |
enum Beverage { 茶, 珈琲, チョコレート } | |
enum Ingredient { 砂糖, ミルク, リキュール } | |
// trick #1: you have to "import static" the enum values for using them as constants | |
// trick #2: in a script, you can actually put imports anywhere, not just at the beginning! | |
import static Beverage.* | |
import static Ingredient.* | |
// our holder for beverage and ingredients | |
class AfternoonBreak { | |
Beverage beverage = null | |
String suffix = '' | |
List<Ingredient> ingredients = [] | |
String toString() { | |
"$beverage ${ingredients ? "(${ingredients.join(', ')}入り)${suffix}" : ''}" | |
} | |
} | |
// our DSL method | |
def 注文するよ(Beverage drink,String suffix) { | |
// our current working beverage | |
def ab = new AfternoonBreak() | |
ab.beverage = drink | |
ab.suffix = suffix | |
// trick #3: store all the drinks in the binding | |
if (!binding.variables.allBreaks) allBreaks = [] | |
allBreaks << ab | |
// trick #4: do the method chaining with nested maps and closures | |
[に: { Ingredient... ings -> | |
ab.ingredients.addAll ings | |
[と: { Ingredient ing -> | |
ab.ingredients << ing | |
}] | |
}] | |
} | |
def わいは(Beverage drink){ 注文するよ(drink,'やで!') } | |
def あたいは、(Beverage drink){ 注文するよ(drink,'だっちゃ!') } | |
def おいらは(Beverage drink){ 注文するよ(drink,'だい!') } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment