It just takes 15 seconds. Send your
details and we’ll get back to you soon.

GroovyShell.evaluate() : The magician behind Grails Console

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!

Share

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Get our latest updates, Subscribe.

By signing up, you agree to our Terms of Service and Privacy Policy.

Categories