Execute Groovy script in Grails

21 / Oct / 2010 by Uday Pratap Singh 0 comments

Working with groovy is really a cake walk. Whenever I get some free time I try to know more about it. Today I was just wondering on the net and I found some cool tips to execute groovy file in grails. There are so many other ways available to run groovy script in grails, I will share one of the way to do it.

To know it we will take a very simple example like we have a groovy script CapitalizeWords.groovy which capitalize all the words of the arguments. The script is like this

List words=[]
this.args.each{arg->
	arg.split().each{
		words.add(it.toUpperCase())
	}
}

return words

Now we will call this script in one of our action like this

def someAction ={
     File file = new File("${servletContext.getRealPath("/")}CapitalizeWords.groovy")
     GroovyShell groovyShell = new GroovyShell()
     def result = groovyShell.run(file, ["Hello ", "this is ", "uday ", "saying Hii to you"])
     render "------${result}------"
}

The output for this would be

------[HELLO, THIS, IS, UDAY, SAYING, HII, TO, YOU]------

In run method of GroovyShell class you pass the file that need to execute and the list of arguments.

Hope it helps
Uday Pratap Singh
uday@intelligrape.com

FOUND THIS USEFUL? SHARE IT

Leave a comment -