Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Example DSL – GeeTwitter


[ 128 ]

To use this method, we can write the following script:


GeeTwitter.search ("Groovy DSL") { from, tweet ->
println "${from} : ${tweet}"
}

Or even better:


import static GeeTwitter.*

search "Groovy DSL"

The classes generated by Groovy scripts are in the default package by default. In
the previous examples, we didn't define a package for the GeeTwitter class, so it
also resides in the default package. When we run the search script, Groovy will
automatically look for any class that we use and compile it, as long as it is in the
same directory as the script that we launch with.


Next, we will look at some more improvements to allow us launch our DSL
scripts from the command line. First, let's fully flesh out the GeeTwitter class
with more methods.


Fleshing out GeeTwitter

The following code is the fully fleshed out GeeTwitter class, with methods for
sending direct messages, along with following and searching methods:


import twitter4j.*
import static twitter4j.TwitterFactory.*

class GeeTwitter {
static sendMessage(user, message) {
// Send a direct messsage to twitter user GroovyDSL
singleton.sendDirectMessage(user, message)
}
// Method to apply a closure to each friend
static eachMessage(Closure c) {
singleton.directMessages.each {
c.call(it.senderScreenName,it.text)
}
}

// Method to apply a closure to each friend
static void eachFriend(Closure c) {
singleton.getFriendsList('fdearle',-1).each {

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