Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert String to GString and replace placeholder in Groovy?

Tags:

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
like image 833
J.T. Avatar asked May 22 '16 20:05

J.T.


People also ask

What is a GString in groovy?

Class GString Represents a String which contains embedded values such as "hello there ${user} how are you?" which can be evaluated lazily.


2 Answers

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.

like image 143
Jacob Aae Mikkelsen Avatar answered Nov 16 '22 23:11

Jacob Aae Mikkelsen


I solved this with Eval:

String stringFromDatabase = 'Hello ${name}!'
String name = 'world'

assert 'Hello world!' == Eval.me('name', name, '"' + stringFromDatabase + '"')
like image 31
Aleksey Krichevskiy Avatar answered Nov 17 '22 00:11

Aleksey Krichevskiy