Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Example DSL – GeeTwitter


[ 130 ]

Improving search

Earlier on, in this chapter, we searched for Tweets from Guillaume LaForge to Graeme
Rocher by passing the string from:glaforge @graemerocher to the Twitter4J Query
method. We could do the same with our simple DSL search method:


search "from:glaforge @graemerocher"

This feels a little clunky, so let's see if there are ways we can improve this interface.
You will remember from Chapter 4, The Groovy Language, the technique we referred
to as named parameters. When we have a method signature in Groovy that includes
a Map, we can omit the brackets around the Map when passing it as a parameter.
Imagine we have a search method that takes a Map as a parameter, then we can
make calls to it as follows:


search from: "glaforge", username: "graemerocher", "Groovy"
search "authentication", from: "alvaro_sanchez", hashtag: "codemotion_
es"

Named parameters allow us to intersperse the String search terms parameter with
the named, Map parameters. In this case, we are using the Map to represent some of
the extended searching features available from the Twitter search API, which we can
implement as follows:


static void search(Map args, String terms = "") {
def queryString = ""
args.each { arg ->
switch (arg.key.toString().toLowerCase()) {
case 'from':
queryString += "from:${arg.value} "
break
case 'to':
queryString += "to:${arg.value} "
break
case 'hashtag':
queryString += "#${arg.value} "
break
case 'username':
queryString += "@${arg.value} "
break
}
}
queryString += terms
def query = new Query(queryString)
singleton.search(query).tweets.each {
println it.text
}
}

http://www.ebook3000.com
Free download pdf