Last updated by dserodio 2 years ago
Tips and Tricks in Grails
Showing a GSP's generated Groovy code
Add showSource to the URL of the grails controller to see the generated Groovy code from the gsp page. Example:http://localhost:8080/App/Controller/list?param1=value1&showSource=trueThis feature only works when executing Grails within the "development" environment. More details here http://www.nabble.com/spillGroovy-argument...-tf2298639.html#a6386846
Quick Tip on Markup Builder example is from a Domain object (Book) that contains enum's if you have only simple datatypes then "render as XML" works just fine
String toXML() { StringWriter buffer = new StringWriter() def xml = new MarkupBuilder(buffer) xml.book() { id(this.id) author(this.authorName) pagecount(pagecount:this.pagecount) } return buffer.toString() + "\\n" }
<book> <id>222</id> <author>Toddecus</author> <pagecount pagecount='99' /> </book>
Quick Tip on parsing say a Rest service that returns the XML above: This assumes you used an XMLSlurper to parse the text into a GPathResult
static Book fromXML(GPathResult bookXML) { def book = new Book() book.id = Integer.parseInt(bookXML.id.text()) book.author = bookXML.author.text() book.pagecount = Integer.parseInt(bookXML.pagecount.@pagecount.text()) return book }
If you really cared about terse XML in your REST service you might even do this:
String toXML() { StringWriter buffer = new StringWriter() def xml = new MarkupBuilder(buffer) xml.book(id: this.id, author:this.authorName, pagecount:this.pagecount){} return buffer.toString() + "\\n" }
<book id='222' author='Toddecus' pagecount='99' />
Enum usage
If you want to use aEnum with a "value" String attribute (a pretty common idiom) in a <select> element, try this:
enum Rating {
G("G"),PG("PG"),PG13("PG-13"),R("R"),NC17("NC-17"),NR("Not Rated") final String value Rating(String value) { this.value = value } String toString() { value }
String getKey() { name() }
}optionKey="key" to your <g:select /> tag. Credit: Gregg Bolinger



