Create dynamically closures in Groovy from a String object

后端 未结 2 678
Happy的楠姐
Happy的楠姐 2021-01-07 03:46

i would like to create a query with the Criteria API in Grails (GORM). The query will have to be something like this:

MyEntity.createCriteria().list{
   asso         


        
2条回答
  •  粉色の甜心
    2021-01-07 04:10

    A more generic approach would be to metaClass String as below, and use it for any kind of separator
    . | , - ~ and more.

    String.metaClass.convertToClosureWithValue = {op, val ->
        split = delegate.split(op) as List
        if(split.size() == 1) {return "Cannot split string '$delegate' on '$op'"} 
    
        items = []
        split.each{
            if(it == split.last()){
                items << "{ eq '$it', $val }"
                split.indexOf(it).times{items.push("}")}
            } else {
                items << "{$it"
            }
        }
    
        println items.join()
        new GroovyShell().evaluate("return " + items.join())
    }
    
    assert "assoc.parent.child.name".convertToClosureWithValue(/\./, "John Doe") instanceof Closure
    assert "assoc-parent-child-name".convertToClosureWithValue(/\-/, "Billy Bob") instanceof Closure
    assert "assoc|parent|child|grandChild|name".convertToClosureWithValue(/\|/, "Max Payne") instanceof Closure
    assert "assoc~parent~child~grandChild~name".convertToClosureWithValue('\\~', "Private Ryan") instanceof Closure
    assert "assocparentchildname".convertToClosureWithValue(/\|/, "Captain Miller") == "Cannot split string 'assocparentchildname' on '\\|'"
    
    //Print lines from items.join()
    {assoc{parent{child{ eq 'name', John Doe }}}}
    {assoc{parent{child{ eq 'name', Billy Bob }}}}
    {assoc{parent{child{grandChild{ eq 'name', Max Payne }}}}}
    {assoc{parent{child{grandChild{ eq 'name', Private Ryan }}}}}
    

提交回复
热议问题