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)

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

* Test Script (Equivalent of the Console UI)

String toBeEvaluated = """

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

Beautifully demonstrates the power of Groovy!

Vivek Krishna

Open Source Enthusiast, Agile Practitioner, Grails Lover, jQuery Worshiper.

Leave a Reply

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

Uday Pratap SinghUday Pratap SinghHitesh Bhatia

You May Also Like

Subscribe to our Blog

Get latest articles straight to your inbox. Enter your email address below: