user3679267
user3679267

Reputation: 1

Closure in Groovy with delegate

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

  1. Why do this?
  2. In which senario we do this.

Upvotes: 0

Views: 567

Answers (1)

injecteer
injecteer

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

Related Questions