I want to read a String from database and replace the placeholder by converting it to a GString. Can I do this with Eval? Any other ideas?
String stringFromDatabase = 'Hello ${name}!'
String name = 'world'
assert 'Hello world!'== TODO
Class GString Represents a String which contains embedded values such as "hello there ${user} how are you?" which can be evaluated lazily.
You can use the Template framework in Groovy, so doing this solves your problem:
String stringFromDatabase = 'Hello ${name}!'
String name = 'world'
def engine = new groovy.text.SimpleTemplateEngine()
assert 'Hello world!'== engine.createTemplate(stringFromDatabase).make([name:name]).toString()
You can find the docs here: http://docs.groovy-lang.org/latest/html/documentation/template-engines.html#_introduction
The GString class is abstract, and the GStringImpl implementation of the abstract class works on the arrays of strings, that it gets from the parsing phase along with values.
I solved this with Eval:
String stringFromDatabase = 'Hello ${name}!'
String name = 'world'
assert 'Hello world!' == Eval.me('name', name, '"' + stringFromDatabase + '"')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With