Last active
December 18, 2015 12:48
-
-
Save jimwhite/5784982 to your computer and use it in GitHub Desktop.
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 Something extends BuilderSupport | |
{ | |
// Convenience build method. | |
// Alternatively you can construct the builder then use it: | |
// def something = new Something().something { ... } | |
static def build(Closure cl) { | |
cl.delegate = new Something() | |
cl.call() | |
} | |
static def print(Object object) { | |
if (object.value) println /*'prefix.' + */ object.name + '=' + object.value | |
object.children.each { print it } | |
} | |
// Using this method means that unresolved symbols are treated as literal strings. | |
// Comment it out if they should be treated normally. | |
def propertyMissing(String property) { property } | |
@Override | |
protected void setParent(Object parent, Object child) { | |
child.name = parent.name + '.' + child.name | |
parent.children = (parent.children ?: []) + child | |
} | |
@Override | |
protected Object createNode(Object name) { | |
[name:name] | |
} | |
@Override | |
protected Object createNode(Object name, Object value) { | |
[name:name, value:value] | |
} | |
@Override | |
protected Object createNode(Object name, Map attributes) { | |
[name:name, attr:attributes] | |
} | |
@Override | |
protected Object createNode(Object name, Map attributes, Object value) { | |
[name:name, attr:attributes, value:value] | |
} | |
} | |
def something = Something.build { | |
something { | |
item1 { | |
prop1 "value1" | |
prop2 "value2" | |
propX symbol1 | |
} | |
item2 { | |
prop3 "value3" | |
prop4 "value4" | |
if (true) { | |
prop5 "value5" | |
} | |
innerItem { | |
foo 1 + 2 | |
bar 3 * 4 | |
propY symbol2 | |
} | |
} | |
} | |
} | |
println something | |
Something.print something | |
/* | |
something.item1.prop1=value1 | |
something.item1.prop2=value2 | |
something.item1.propX=symbol1 | |
something.item2.prop3=value3 | |
something.item2.prop4=value4 | |
something.item2.prop5=value5 | |
something.item2.innerItem.foo=3 | |
something.item2.innerItem.bar=12 | |
something.item2.innerItem.propY=symbol2 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment