通过域类绑定在运行时评估GSTRING



我想存储一个可以绑定到域类的用户可配置的GSTRING,但我遇到了一个问题,找到一个很好的解决方案。

示例(概念/伪/非工作

class Person{
    ...
    String displayFooAs;  //<-- contains a java.lang.String like '${name} - ${address}'
}

class Foo{
    String name;
    String address;
    String city;
    public String getDisplayAs(def person){
        return doStuff(this, person.displayFooAs); //<-- Looking for something simple.
    }

}

更新:

审查后,我决定这种灵活性会带来安全风险。它将允许用户本质上将SQL注入脚本录入" DispalyFooas"。返回绘图板。

您的意思是:

public String getDisplayAs(def person){
  doStuff( this, person?.displayFooAs ?: "$name - $address" )
}

这在Groovy中起作用,但是我从来没有将SimpleTemplateEngine嵌入到Grails中,因此需要进行大量测试以确保其按预期工作并且不会吞噬存储器。

import groovy.text.SimpleTemplateEngine
class Person {
  String displayAs = 'Person $name'
}
class Foo {
  String name = 'tim'
  String address = 'yates'
  String getDisplayAs( Person person ) {
    new SimpleTemplateEngine()
          .createTemplate( person?.displayAs ?: '$name - $address' )
          .make( this.properties )
          .toString()
  }
}
def foo = new Foo()
assert foo.getDisplayAs( null )         == 'tim - yates'
assert foo.getDisplayAs( new Person() ) == 'Person tim'

您已经定义了

private static final String DEFAULT_DISPLAY_AS = '${name} - ${address}'

static final - 当然不起作用?

将其定义为闭合

private def DEFAULT_DISPLAY_AS = {->'${name} - ${address}'}

并致电代码

DEFAULT_DISPLAY_AS()

我需要类似的东西,其中我会在闭合环内评估gstring,以便模板引用其属性值。我以上面的例子为例,将其正式化为标准化类,以进行晚期GSTRING评估。

import groovy.text.SimpleTemplateEngine
class EvalGString {
    def it
    def engine
    public EvalGString() {
        engine = new SimpleTemplateEngine()
    }
    String toString(template, props) {
        this.it = props
        engine.createTemplate(template).make(this.properties).toString()        
    }
}    
def template = 'Name: ${it.name} Id: ${it.id}'
def eval = new EvalGString()
println eval.toString(template, [id:100, name:'John')
println eval.toString(template, [id:200, name:'Nate')

输出:

名称:约翰ID:100

名称:NATE ID:200

最新更新