Last active
August 29, 2015 14:05
-
-
Save darylteo/fbdc989f91c18394aaa8 to your computer and use it in GitHub Desktop.
A Map + Expando implementation for Groovy
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
import groovy.json.*; | |
class MyBean extends Expando { | |
def methodMissing(String name, def args) { | |
if(args.size() == 0) { | |
super.getProperty(name) | |
} else if(args.size() == 1) { | |
def value = args[0]; | |
def result = value; | |
if(value instanceof Closure) { | |
result = new MyBean(); | |
value.delegate = result; | |
value.resolveStrategy = Closure.DELEGATE_FIRST; | |
value.call(result); | |
} | |
super.setProperty(name, result); | |
} else { | |
throw new MissingMethodException(name, MyBean.class, args) | |
} | |
} | |
def toMap() { | |
return this.getProperties(); | |
} | |
} | |
def bean = new MyBean(); | |
println bean.foo | |
bean.foo = "Bar" | |
println bean.foo | |
println bean.foo() | |
bean.foo("Hello") | |
println bean.foo | |
println bean.foo() | |
bean.foo { | |
hello 'World' | |
} | |
bean.foo.bar = "Hey" | |
println bean.foo | |
bean.foo.hello = "Blah!" | |
println bean | |
println bean.toMap() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment