Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access variable value by its name as String (groovy)

Tags:

groovy

eval

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

like image 348
GiLA3 Avatar asked May 16 '26 19:05

GiLA3


2 Answers

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]) }
like image 97
dsharew Avatar answered May 21 '26 05:05

dsharew


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

like image 40
Rao Avatar answered May 21 '26 05:05

Rao