Created
August 12, 2014 18:33
-
-
Save jimwhite/f0bee9299bde7ff8efa9 to your computer and use it in GitHub Desktop.
This file contains 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
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