gpt4 book ai didi

grails - 使用域类绑定(bind)在运行时评估 GString

转载 作者:行者123 更新时间:2023-12-02 14:45:16 25 4
gpt4 key购买 nike

我想存储一个用户可配置的 GString ,该 GString 将绑定(bind)到一个域类,但我在找到一个很好的解决方案时遇到了问题。

示例( 概念/伪/非工作 )

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.

}



}

更新:

经过审查,我决定这种灵 active 将构成 安全风险 .它将允许用户基本上将 sql 注入(inject)脚本写入“dispalyFooAs”。回到绘图板。

最佳答案

你的意思是像:

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

这在 Groovy 中有效,但我从未在 Grails 中将 SimpleTemplateEngine 嵌入到类似的东西中,因此需要进行大量测试以确保它按预期工作并且不会占用内存。
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'

关于grails - 使用域类绑定(bind)在运行时评估 GString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13123354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com