issue getting dynamic Config parameter in Grails taglib
I have a dynamic config parameter I want to get like:
String srcProperty = "${attrs ['src']}.audio" + ((attrs['locale'])? "_${attrs['locale']}" : '')
assert srcProperty == "prompt.welcomeMessageOverrideGreeting.audio"
where my config has:
prompt{
welcomeMessageOverrideGreeting开发者_StackOverflow中文版 {
audio = "/en/someFileName.wav"
txt = "Text alternative for /en/someFileName.wav"
audio_es = "/es/promptFileName.wav"
txt_es = "Texto alternativo para /es/someFileName.wav"
}
}
While this works fine:
String audio = "${config.prompt.welcomeMessageOverrideGreeting.audio}"
and: assert "${config.prompt.welcomeMessageOverrideGreeting.audio}" == "/en/someFileName.wav"
I can not get this to work:
String audio = config.getProperty("prompt.welcomeMessageOverrideGreeting.audio")
They're not stored flat like that, they're stored hierarchically. "config.prompt.welcomeMessageOverrideGreeting.audio" is a shorthand to get "prompt" from config, then "welcomeMessageOverrideGreeting" from that, then "audio" from that. If you want to use dot notation just flatten the config:
String audio = config.flatten().getProperty("prompt.welcomeMessageOverrideGreeting.audio")
SOLVED: This was REALLY tough, but here is what I found that worked to get a dynamic property:
String audio = srcProperty.tokenize( '.' ).inject( config ) { cfg, pr -> cfg[ pr ] }
I blogged about it: http://www.baselogic.com/blog/development/grails-groovy-development/configslurper-with-dynamic-property-name-from-configurationholder-config-object
Assuming myconfig.groovy
in classpath:
prompt{
welcomeMessageOverrideGreeting {
audio = "/en/someFileName.wav"
txt = "Text alternative for /en/someFileName.wav"
audio_es = "/es/promptFileName.wav"
txt_es = "Texto alternativo para /es/someFileName.wav"
}
}
We can get properties constructing their names dynamically:
def myconfig = this.class.getResource("/myconfig.groovy")
def config = new ConfigSlurper().parse(myconfig)
def dynamic = "welcomeMessageOverrideGreeting"
def dynamic2 = "audio"
def locale = "es"
assert config.prompt[dynamic].audio == "/en/someFileName.wav"
assert config.prompt.welcomeMessageOverrideGreeting[dynamic2] == "/en/someFileName.wav"
assert config.prompt.welcomeMessageOverrideGreeting["${dynamic2}_${locale}"] == "/es/promptFileName.wav"
assert config.prompt[dynamic]["${dynamic2}_${locale}"] == "/es/promptFileName.wav"
精彩评论