Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
// sample entity
class User{
 def username, password, version, salt = 'RANDOM';
}

// your API, provide a Map of changes to update a entity. the map value may be static value, or a closure that take zeroup to 2 params
def update( entity, Map changes ){
 
 changes?.each {k, v ->
  def newValue;
  if (v instanceof Closure){
   switch (v.parameterTypes.length) {
    case 0: newValue = v(); break;
    case 1: newValue = v(entity[k]); break; // if one params, the closure is called with the field value
    case 2: newValue = v(entity[k],entity); break; // if two params, the closure is called with teh field value and the entity
   }
  }else{
   newValue = v
  }
  entity[k] = newValue
 }
}

// user code
def user1 = new User(username:'user1', password:'pass1', version:0)
update( user1, [password:{vp,e-> Hash.md5(vp, e.salt) }, version:{v-> v+1 }] //assume there is a MD5 util

Other Examples

  • You could define a closure that take a closure as argument, and combine the use of other Groovy techniques to do a lot of things. See the Closure, Category and JPA example

...