grails - Groovy 中的闭包与委托(delegate)

标签 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 获取参数名称,然后代码拆分参数名称,然后使用 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/

    相关文章:

    spring - 将 Camel 2.1 与 Grails 1.2.1 一起使用 - 类加载问题

    Grails Mail 插件 sendMail 钩子(Hook)

    maven - IntelliJ Idea 14 在 grails 应用程序调试中出错

    mysql - Grails 实体更改我的表并创建新表

    grails - 在 Grails 中,如何获取包含请求参数的请求 URI?

    Javascript 树无法正常工作

    grails - Grails可搜索插件找不到导入的MySQL数据

    validation - Grails,如果我发现错误,如何从域发送消息(类型 flash)?

    grails - Grails创建例程

    Grails Spring 安全 : how to undo s2-quickstart