Created
June 10, 2014 14:17
-
-
Save deigote/2234981b9ec74b16b7f5 to your computer and use it in GitHub Desktop.
Groovy - ExpandoWithDelegate
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
class ExpandoWithDelegate { | |
private delegate | |
private Map<String, Closure> mockedMethods | |
ExpandoWithDelegate(delegate) { | |
this.delegate = delegate | |
this.mockedMethods = [:] | |
} | |
def methodMissing(String name, args) { | |
mockedMethods.containsKey(name) ? | |
mockedMethods[name](*args) : | |
delegate."$name"(*args) | |
} | |
def propertyMissing(String name, value) { | |
if (value instanceof Closure) { | |
value.delegate = delegate | |
mockedMethods[name] = value | |
} | |
else throw new MissingPropertyException(name, delegate.getClass()) | |
} | |
} | |
def var = new ExpandoWithDelegate('me molo') | |
assert var.size() == 7 | |
var.size = { -> 42 } | |
assert var.size() == 42 | |
assert var.concat(' mucho') == 'me molo mucho' | |
var.concat = { anotherString -> delegate.concat(anotherString).concat('!!!') } | |
assert var.concat(' mucho') == 'me molo mucho!!!' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment