Skip to content

Instantly share code, notes, and snippets.

@lucastelnovo
Last active December 19, 2015 10:09
Show Gist options
  • Select an option

  • Save lucastelnovo/5938041 to your computer and use it in GitHub Desktop.

Select an option

Save lucastelnovo/5938041 to your computer and use it in GitHub Desktop.
Implementación de la clase 'Prototipos' for dummies. Hecha con 'withParams'. Very verbose. Full comments.
class Prototipos {
static init() {
Object.metaClass {
// Necesito 'prototipos' porque ahora tengo más de uno.
prototipos = null
dynamicProperties = null
propertyMissing = { String name, value ->
dynamicProperties[name] = value
}
propertyMissing = { String name ->
if(dynamicProperties.containsKey(name)){
return dynamicProperties[name]
} else {
/*
* Acá esta el mayor cambio a diferencia de con un solo
* prototipo: para cada prototipo en la lista de prototipos
* le pido la property. Me la devuelve en el primero que la
* encuentra.
*/
for (prototipo in prototipos) {
try {
return prototipo."$name"
} catch (MissingPropertyException e) {
}
}
}
throw new MissingPropertyException(name, delegate.getClass())
}
/*
* Necesito éste método para agregar a la lista
* de prototipos de un objeto.
*/
addPrototype = { aPrototype ->
prototipos.add(aPrototype)
}
methodMissing = { String name, args ->
try {
def bloque = delegate."$name"
delegate.withParams(bloque, args)
} catch(MissingPropertyException e){
throw new MissingMethodException(name, delegate.getClass(), args)
}
}
def oldConstructor = Object.metaClass.retrieveConstructor()
constructor = {
def newInstance = oldConstructor.newInstance()
newInstance.dynamicProperties = [:]
// Acá también le seteo una lista de prototipos a la nueva instancia.
newInstance.prototipos = []
newInstance
}
withParams = { closure, Object... params ->
final Closure clonedClosure = closure.clone();
clonedClosure.setResolveStrategy(Closure.DELEGATE_FIRST);
clonedClosure.setDelegate(delegate);
clonedClosure.call(*params);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment