lunedì 27 gennaio 2014

Idea 12 : How to write a live template with groovyscript inside

With Intellij Idea 12 you can write live templates (interesting post about this feature):

Live templates contain predefined code fragments. You can use them to insert frequently-used or custom code constructs into your source code file quickly, efficiently, and accurately.
(taken from official documentation)

in live template code you can use the groovyScript in expressions of variables to launch embedded groovy script code

with groovy script code you can evaluate templates with much more logic than with the template

to do this you must define a variable in the template text, for example you can use $GROOVY$, and then define the groovy script code using "edit variables"

after clicking it you can see a row for the GROOVY variable
Idea screenshot

you can now define groovy script editing expression field.

for example:

groovyScript("def result=\"from live template! method name ${_1}\"; return result", methodName())

in this sample groovyscript can access methodName using _1

there is a problem ... you must write all you script on a one-line! (I didn't find a way to write multi line code at the moment)

now I'll write a live template called 'logstart' which prints log.info( "<methodname>", "<parameters>")
where parameters will be in the form of <parametername>:${<paramtername>}

groovyScript("def parameters=''; def result='log.info(\"'+_2+'\",\"'; _1.each { parameters+=it+':${'+it+'},'}; result+=parameters[0..-2]+'\")'; return result",methodParameters(),methodName())

now writing logstart and pressing Tab in a method I have a log.info writing all the parameters received

1 commento:

  1. > there is a problem ... you must write all you script on a one-line!

    Actually it's possible to run scripts from a file like this:
    groovyScript("/Users/alsk/bin/test.groovy", className(),methodName())

    RispondiElimina