使用委托关闭Groovy

时间:2014-05-30 07:32:27

标签: grails

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取params名称,然后代码拆分param名称,然后使用ilike运算符检查,但是当获取shiro使用代码时,请执行此u.delegate =委托,然后调用u()闭包。请解释一下

  1. 为什么这样?
  2. 我们在哪个参议员。

1 个答案:

答案 0 :(得分:1)

代码有效地将闭包链接在一起:

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()
}

另一个强调闭包授权的例子是:

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。在这里,您可以将条件查询定义为闭包,并重新使用它来获取结果和计数。