Skip to content

Instantly share code, notes, and snippets.

@jimwhite
Created August 12, 2014 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimwhite/f0bee9299bde7ff8efa9 to your computer and use it in GitHub Desktop.
Save jimwhite/f0bee9299bde7ff8efa9 to your computer and use it in GitHub Desktop.
def evaluator = new CachingEvaluator()
assert evaluator.evaluate("1 + 2 * 3") == 7
assert evaluator.evaluate("1 + 2 * ${3}") == 7
assert evaluator.evaluate(new String("1 + 2 * 3")) == 7
assert evaluator.compiledScriptClasses.size() == 1
class CachingEvaluator {
GroovyShell shell = new GroovyShell()
Map<String, Class> compiledScriptClasses = [:]
Object evaluate(String scriptSource) {
Class klazz = compiledScriptClasses[scriptSource]
if (klazz == null) {
klazz = shell.parse(scriptSource).getClass()
compiledScriptClasses[scriptSource] = klazz
}
Script script = (Script) klazz.newInstance()
script.setBinding(shell.getContext())
script.run()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment