Krystian
Krystian

Reputation: 3423

How to get groovy to evaluate ${sth} when stored in string?

I'm getting a text which contains ${somethingElse} inside, but it's just a normal String.

I've got a class:

class Whatever {

    def somethingElse = 5

    void action(String sth) {
        def test = []
        test.testing = sth
        assert test.testing == 5

    }
}

Is it possible with groovy?

EDIT:

my scenario is: load xml file, which contains nodes with values pointing to some other values in my application. So let's say I've got shell.setVariable("current", myClass). And now, in my xml I want to be able to put ${current.someField} as a value. The trouble is, that the value from xml is a string and I can't evaluate it easily. I can't predict how these "values" will be created by user, I just give them ability to use few classes.

I cannot convert it when the xml file is loaded, it has to be "on demand", since I use it in specific cases and I want them to be able to use values at that moment in time, and not when xml file is loaded.

Any tips?

Upvotes: 0

Views: 529

Answers (2)

Krystian
Krystian

Reputation: 3423

At first, what we did, was used this format in xml:

normalText#codeToExecuteOrEvaluate#normalText

and used replace closure to regexp and groovyShell.evaluate() the code. Insane. It took a lot of time and a lot of memory.

In the end we changed the format to the original one and crated scripts for each string we wanted to be able to evaluate:

Script script = shell.parse("\""+stringToParse+"\"")

where

stringToParse = "Hello world @ ${System.currentTimeMillis()}!!"

Then we were able to call script.run() as many times as we wanted and everything performed well. It actually still does.

Upvotes: 0

tim_yates
tim_yates

Reputation: 171084

One thing you could do is:

class Whatever {

  def somethingElse = 5

  void action( String sth ) {
    def result = new groovy.text.GStringTemplateEngine().with {
      createTemplate( sth ).make( this.properties ).toString()
    }
    assert result == "Number 5"
  }
}

// Pass it a String
new Whatever().action( 'Number ${somethingElse}' )

Upvotes: 2

Related Questions