GroovyShell.evaluate() : The magician behind Grails Console

05 / Sep / 2012 by Vivek Krishna 0 comments

Grails console is one plugin that we install as soon as we create a new application. The power and the purpose of the utility is too good to be missed. On one such occasion, I decided to dig the code in the plugin and discovered the magic trick that executes the string that we type in the web interface.

Turned out that GroovyShell.evaluate() method is the superstar.

To validate the same, I put together a class and script which is simply an arithmetic expression evaluator which can take either implicit variables(declared in the code body) or assumed values of variables(sent in bindings to the GroovyShell). While the former is apparent, the latter means that we assume some variables/values to be understood while the script is being executed. We assign those objects to the Shell via groovy.lang.Binding

* Evaluator Class (The equivalent of ConsoleService)

[java]

class ArithmeticEvaluator {
static def evaluate(String expr, Map bindings){
new GroovyShell(new Binding(bindings)).evaluate(expr)
}
}

[/java]

* Test Script (Equivalent of the Console UI)

[java]
String toBeEvaluated = """

Integer x = 10
BigDecimal y = 20
return x*y + (x + y) + z
"""
println(ArithmeticEvaluator.evaluate(toBeEvaluated, [z:5])) // prints 235
[/java]

Beautifully demonstrates the power of Groovy!

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *