Monday, 30 March 2009

Being Groovy

Nothing spectacular here, but it's interesting to see just how nice and simple Groovy can be. I have a page in my app where the user can tick a checkbox for each of their networks to say which networks should receive a status update. The request looks something like this:
newStatus=hello%20world!&network1=on&network2=on&network3=on

Grails supplies this as a map called params, but what I really want is a simple list of network ID's. Here's how I do it:
def networkIds = params.findAll({ key, val ->
key.startsWith("network")
}).collect({ key, val ->
Integer.parseInt(key[7..-1])
})

Basically, I'm chaining two calls together - findAll + collect - that both accept a closure. I'm using findAll to filter out any entries that don't start with 'network' and then collect to convert the resulting map into a list of ints. And not an iterator in sight!

No comments: