Skip to content

Instantly share code, notes, and snippets.

@rhyolight
Created January 25, 2009 14:13
Show Gist options
  • Save rhyolight/51792 to your computer and use it in GitHub Desktop.
Save rhyolight/51792 to your computer and use it in GitHub Desktop.
How Grails-UI turns groovy data structures into JavaScript data structures.
/**
* Turns map into a javascript config object string for YUI. This is what allows configurations passed into the
* grailsUI tag to be passed along to the YUI widget.
*/
def mapToConfig(attrs) {
attrs.collect { key, val ->
// if this is a handler, the val will be a javascript function, so don't quote it
if (key == 'handler') return "$key: $val"
"'$key': ${valueToConfig(val)}"
}.join(",\n")
}
def listToConfig(list) {
list.collect {
if (it instanceof Map) {
return "{" + mapToConfig(it) + "}"
}
"'$it'"
}.join(", ")
}
def valueToConfig(val) {
if (val instanceof String || val instanceof GString) {
// if this string resolves to a number, also don't quote it
if (val.isNumber()) return val
// if string starts with '@', that means this is a javascript object reference, and we shouldn't quote it
if (val.startsWith('@')) return val - '@'
return "'$val'"
} else if (val instanceof Map) {
return "{${mapToConfig(val)}}"
} else if (val instanceof List) {
return "[${listToConfig(val)}]"
}
val
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment