Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Example DSL – GeeTwitter


[ 122 ]

The Twitter4J APIs refer to the users you follow as friends and those following you as
followers. This certainly clears up the confusion a little bit. However, users on Twitter
don't necessarily know, or seldom care about, who is following them. So, calling
them friends who eavesdrop on all their conversations is a little like stalking.
Anyway, we can use the APIs to list all of our friends or followers, or to create a
new friendship (in other words follow another user):


def twitter = TwitterFactory.singleton
// Get a list of my followers
def friends = twitter.getFriendsList('groovydsl',-1)
friends.each { friend ->
// Print each screen name
println friend.screenName
}
// "Follow" the Twitter user GroovyDSL
twitter.createFriendship("GroovyDSL")

Here we use the Twitter.getFriendsList method to retrieve the list of users that
we are currently following. Iterating this list, we can print the screen names of all of
these users. Finally, we use the Twitter.createFriendship method to start stalking
the user GroovyDSL. This is a user that I set up while writing this book and testing
out these scripts. Feel free to run this script and start following me yourself. I just
can't guarantee that it won't be a Twitter bot written in the Groovy DSL that updates
this user!


Groovy improvements


So far we have been using Twitter4J as a vanilla API, with a smattering of Groovy, so
we have not been bringing any of the Groovier features to bear. Now that we know a
little bit about the API, let's try to improve our usage by using some Groovy features.
In this section, we will progressively improve our usage of the Twitter4J APIs by
selectively using the features that Groovy provides. One of the most obvious features
to use is closures.


A Groovier way to find friends


In the previous examples, we iterated over our friends and printed out their
details. What if we were to provide a method that takes a closure to apply to each
friend or follower? In this example, we add these methods to a script, along with a
follow method, to follow another Twitter user. We can use the eachFollower or
eachFriend methods to list our current connections:


followersList = { user ->
TwitterFactory.singleton.getFollowersList(user,-1)

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