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

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

return words
[/java]

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

[java]
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}——"
}
[/java]

The output for this would be
[java]
——[HELLO, THIS, IS, UDAY, SAYING, HII, TO, YOU]——
[/java]

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 Reply

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