J.T.
J.T.

Reputation: 351

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

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

Upvotes: 22

Views: 11463

Answers (4)

Diego Ballve
Diego Ballve

Reputation: 11

This also uses the Templates as Jacob's answer, but tries to resolve binding from current variables. Useful if you don't know what value you are replacing:

String stringFromDatabase = 'Hello ${name}!'
// variables w/o type or def keyword end up in this.binding.variables
name = 'world'

def engine = new groovy.text.SimpleTemplateEngine()
assert 'Hello world!'== engine.createTemplate(stringFromDatabase).make(this.binding.variables).toString()

CAVEAT: variables that can be replaced don't have type or def keyword.

Upvotes: 0

Aleksey Krichevskiy
Aleksey Krichevskiy

Reputation: 136

I solved this with Eval:

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

assert 'Hello world!' == Eval.me('name', name, '"' + stringFromDatabase + '"')

Upvotes: 2

Jacob Aae Mikkelsen
Jacob Aae Mikkelsen

Reputation: 579

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.

Upvotes: 18

Psycho Punch
Psycho Punch

Reputation: 6892

You should be using double quoted String literal if you want to use place holders.

The following should work:

String name = 'world'
String stringFromDatabase = "Hello ${name}!" //use double quotes

assert 'Hello world!' == stringFromDatabase

See the official Groovy documentation about Strings to see other ways you can make this work.

Upvotes: -2

Related Questions