views:

384

answers:

3

Hi all,

I'm currently facing a variable substitution related problem in groovy. While this is quite trivial:

Map map = [s1:"Hello", s2:"World"]
println "${map.s1} ${map.s2}!" // "Hello World!"

As this works, I'm pretty sure that something like this should work as well:

Map map = [s1:"Hello", s2:"World"]
def dynamic = loadStringFromFile();

println "${dynamic} ${dynamic.class}" // "${s1} ${s2}! (java.lang.String)"

// now the voodoo part
println applyVoodoo(dynamic, map) // "Hello World!"

Does anybody know how to get this working?

Cheers

A: 

Try

def dynamic = new GString (loadStringFromFile())
println dynamic
Aaron Digulla
GString is abstract: "You cannot create an instance from the abstract class 'groovy.lang.GString'"btw, I'm using Groovy Version: 1.6.4 JVM: 1.6.0_16
sfussenegger
+2  A: 
dynamic.replaceAll(/\$\{(\w+)\}/) { m, k -> map[k] }
sepp2k
This works, thanks!However, as I was looking for something that's closer to using static strings, I came up with another solution:def applyVoodoo(String str, Map map) { Binding b = new Binding(); for (e in map) b.setVariable(e.key, e.value); GroovyShell sh = new GroovyShell(b); return sh.evaluate("\"${str}\"");}
sfussenegger
re: Binding. This is a good approach and a very powerful tool. Note that you can pass the map in to the Binding constructor (for 1.6.4 at least).
Michael Easter
+1  A: 

You would normally do this with Groovy Templates.

John Wagenleitner
thanks, that was definitely what I was looking for!
sfussenegger