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()
}
闭包 u 获取参数名称,然后代码拆分参数名称,然后使用 ilike 运算符进行检查,但是在获取 shiro 使用代码时执行此 u.delegate = delegate 然后调用 u() 闭包。请解释一下
最佳答案
该代码有效地将闭包链接在一起:
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()
}
另一个强调闭包委托(delegate)的例子是:
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()
}
这样做的原因是 DRY。在这里,您可以将条件查询定义为闭包并重新使用它来获取结果和计数。
关于grails - Groovy 中的闭包与委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23949332/