Tuesday, September 4, 2012

Tip: Dynamically execute a groovy script



You can execute a dynamically generated groovy script or a script stored in a text file or variable using GroovyShell. See example below


def script = ''' def x = 'my dynamically' def y = ' executed script' return x << y ''' def shell = new GroovyShell() def result = shell.evaluate(script) println result
The above script would print "my dynamically executed script" If you want to pass variable to your script, you can make use of binding variables. See below

def script = ''' def code1 = """${crypto.code1}""" def code2 = """${crypto.code2}""" return code1 << ' ' << code2 ''' def crypto = [code1:'my dynamically',code2:'executed script'] def shell = new GroovyShell( new Binding(crypto:crypto) ) def result = shell.evaluate(script) println result
For those who are new to groovy operator << is for creating StringBuffer

No comments:

Post a Comment