Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 6

[ 127 ]

TwitterFactory.singleton.search(query).tweets.each {
println it.text
}
}

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 write a script that uses these search methods, as follows:


def gTwitter = new GeeTwitter()

gTwitter.search "Groovy DSL"

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

Although this is fine for most circumstances, we would like to make the ending DSL
scripts as clear and to the point as possible so that a non-programmer might be able
to write them. The need to create a GeeTwitter object before we can use the method
is more unnecessary boilerplate. If, instead, we make the method static, the usage of
the method is much clearer to the average user:


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

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