Java Reference
In-Depth Information
bling the elements into a string. To create a query string, invoke join with an ampersand
as an argument:
["cht=p3", "chs=250x100", "chd=t:60,40", "chl=Hello|World"].join('&')
The result is the needed query string, as shown here:
"cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World"
Here's the entire process so far, taking the base URL and the parameter map, and building
the Google Chart URL:
String base = 'http://chart.apis.google.com/chart?'
def params = [cht:'p3',chs:'250x100',
chd:'t:60,40',chl:'Hello|World']
String qs = params.collect { k,v -> "$k=$v" }.join('&')
The result of all this manipulation is actually a string, not a URL. Before converting it to
a URL, let me first verify that the process worked. Normally this would require a test, as
discussed extensively in chapter 6 on testing. Here, however, I'll just use the Groovy as-
sert keyword, which takes a boolean expression as an argument. If the expression is true,
nothing is returned, but if not, you get the error printed to the console. In this case I'll use
the contains method from the Map interface to check that each of the entries from the
params map appears in the query string in the proper format:
params.each { k,v ->
assert qs.contains("$k=$v")
}
The assert keyword
Groovy asserts are an easy way to verify correctness. An assert returns nothing if the ex-
pression is true, and prints a detailed error message if it's not.
One of the advantages of the join method is that you don't have to worry about accident-
ally adding an ampersand at the beginning or end of the string. It only adds the separator
internally.
Search WWH ::




Custom Search