GiLA3
GiLA3

Reputation: 419

Access variable value by its name as String (groovy)

I've done some research but I haven't found a working code for my case. I have two variables named test and test2 and I want to put them in a map in the format [test:valueof(test), test2:valueof(test2)]

My piece of code is the following:

def test="HELLO"
def test2="WORLD"
def queryText = "\$\$test\$\$ \$\$test2\$\$ this is my test"

def list = queryText.findAll(/\$\$(.*?)\$\$/)

def map = [:]
list.each{
    it = it.replace("\$\$", "")
    map.putAt(it, it)
}

queryText = queryText.replaceAll(/\$\$(.*?)\$\$/) { k -> map[k[1]] ?: k[0] }

System.out.println(map)
System.out.println(queryText)

Output:

output

Desired output:

"HELLO WORLD this is my test"

I think I need something like map.putAt(it, eval(it))

EDIT

This is the way I get my inputs. the code goes into the 'test' script

The ones on the right are the variable names inside the script, the left column are the values (that will later be dynamic)

enter image description here enter image description here

Upvotes: 3

Views: 10236

Answers (3)

GiLA3
GiLA3

Reputation: 419

Final working code, thanks to all, in particular to dsharew who helped me a lot!

#input String queryText,test,test2,test3

def list = queryText.findAll(/\$\$(.*?)\$\$/)

def map = [:]
list.each{
    it = it.replace("\$\$", "")
    map.putAt(it, it)
}

queryText = queryText.replaceAll(/\$\$(.*?)\$\$/) { k ->  evaluate(k[1]) }

return queryText

Upvotes: 1

dsharew
dsharew

Reputation: 10675

You are almost there.
The solution is instead of putting the values into separate variables put them into the script binding.

Add this at the beginning ( remove the variables test and test2):

def test="HELLO"
def test2="WORLD"
binding.setProperty('test', test)     
binding.setProperty('test2', test2)  

and change this:

{ k -> map[k[1]] ?: k[0] }

to this:

{ k ->  evaluate(k[1]) }

Upvotes: 4

Rao
Rao

Reputation: 21389

It should be very simple if you could use TemplateEngine.

def text = '$test $test2 this is my test'
def binding = [test:'HELLO', test2:'WORLD']
def engine = new groovy.text.SimpleTemplateEngine() 
def template = engine.createTemplate(text).make(binding)
def result = 'HELLO WORLD this is my test'
assert result == template.toString()

You can test quickly online Demo

Upvotes: 1

Related Questions