Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Example DSL – GeeTwitter


[ 124 ]

We can write a neat auto-follow script. In the following example, we will use
eachFollower to apply a closure to each of our followers. The closure method
determines if we are already a friend of this follower simply by using the Groovy
collections any, and follows the follower if we are not:


// Auto follow
eachFollower { follower ->
// If any of my friends is this follower
if (twitter.friends.any { friend ->
friend.screenName == follower
})
return;
// Otherwise follow him
println "Following ${follower}"
follow(twitter, follower)
}

Twitter throws an exception if we try to follow a user that we are already following.
In the Auto follow closure shown in the previous code snippet, we first checked to
see if any of our friends is a follower before trying to follow him or her.


Groovy searching

In the same vein, we can also add a search method taking a closure:


void search(terms, Closure c) {
def query = new Query(terms)
TwitterFactory.singleton.search(query).tweets.each {
c.call(it.user.screenName,it.text)
}
}

We can pass a closure to the search method in order to print out the details of the
tweets that we find:


// Print all recent tweets about Groovy and DSL
search ("Groovy DSL") { from, tweet ->
println from + " : " + tweet
}

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