Skip to content

Instantly share code, notes, and snippets.

@eclecticlogic
Created September 26, 2014 17:51
Show Gist options
  • Save eclecticlogic/2b8a8d78dab281a26378 to your computer and use it in GitHub Desktop.
Save eclecticlogic/2b8a8d78dab281a26378 to your computer and use it in GitHub Desktop.
Groovy DSL executor using supplied handler
class DSLExecutor {
/**
* @param filename Groovy file to execute.
* @param handler Handler that provides implementations for methos and properties the script references.
* @return A map of variables returned. The keys are the names of the variables.
*/
static Map<String, Object> execute(String filename, Object handler) {
ResourceLoader loader = new DefaultResourceLoader();
String scriptSource = loader.getResource(filename).getInputStream().getText()
Binding binding = new Binding()
Script script = new GroovyShell().parse(scriptSource)
script.setBinding(binding)
// We use the metaclass method and property resolution to route calls to the handler.
// Route missing methods to the handler.
script.metaClass.methodMissing = {String name, args ->
MetaMethod method = handler.metaClass.getMetaMethod(name, args)
if (method) {
method.invoke(handler, args)
} else {
throw new MissingMethodException("No method $name found", handler.class, args)
}
}
// route missing properties to the handler
script.metaClass.propertyMissing = {String name, value ->
MetaProperty property = handler.metaClass.getMetaProperty(name)
if (property) {
return property.getProperty(handler)
} else {
throw new MissingPropertyException("No property $name found", handler.class)
}
}
script.run()
return binding.getVariables();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment