Reputation: 1
Closure u = {
if (params?.searchName) {
def name = params?.searchName?.split(' ').toList()
or {
name.each {
ilike('firstName', "%${it}%")
ilike('lastName', "%${it}%")
}
}
}
def count = ShiroUser.createCriteria().get() {
projections {
count "id"
}
u.delegate = delegate
u()
}
The closure u takes the params name and then code split the param name and then check using ilike operator but then when getting the shiro use code do this u.delegate = delegate and then call u() closure. Please explain this
Upvotes: 0
Views: 567
Reputation: 20707
the code effectively chains the closures together:
def count = ShiroUser.createCriteria().get() {
projections {
count "id"
}
// Here you set the "context" of the 'u' closure to the current "context" of criteria query
u.delegate = delegate
// here you run the 'u' closure and extend the criteria query with ilike search by name
u()
}
Another example to highlight the closure delegation would be:
Closure u = {
// the closure from above
}
Closure counter = {
projections {
count "id"
}
}
def count = ShiroUser.createCriteria().get() {
counter.delegate = delegate
counter.call() // same as counter()
u.delegate = delegate
u()
}
The reason to do this is DRY. Here you can define a criteria query as a closure and re-use it for getting the results AND count.
Upvotes: 1