Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 6

[ 129 ]

c.call(it.screenName)
}
}

// Method to apply a closure to each follower
static void eachFollower(Closure c) {
singleton.getFollowersList('fdearle',-1).each {
c.call(it.screenName)
}
}

// Method to follow another twitter user
static void follow(user) {
singleton.createFriendship(user)
}

static void search(terms) {
def query = new Query(terms)
singleton.search(query).tweets.each {
println it.text
}
}

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

Now, if we launch the GroovyConsole from the same directory as this class and
add the Twitter4J JAR from the class path, we can start experimenting with our
fully-fledged Twitter DSL interactively. Here we can issue a search for the terms
"Groovy DSL" and see the result directly within the console output pane.


In the following snippet, we will see how the auto follow script has been reduced
to one line. By removing all boilerplate and handling the follow method within
our own DSL method, we can eliminate the need for the user to care about any
exceptions that might be thrown. Auto follow becomes one elegant line of script:


import static GeeTwitter.*

eachFollower { follow it }
Free download pdf