2017-04-18 62 views
1

讓我們說我有以下命令:Groovy的2.4.4命令對象 - 重用驗證閉合

@Validateable 
class MyCommand { 
    String cancel_url 
    String redirect_url 
    String success_url 

    static constraints = { 
     cancel_url nullable: false, validator: { url, obj -> 
      //some specific validation 
      //some common url validation 
     } 
     redirect_url nullable: false, validator: { url, obj -> 
      //some specific validation 
      //some common url validation 
     } 
     success_url nullable: false, validator: { url, obj -> 
      //some specific validation 
      //some common url validation 
     } 
    } 
} 

比方說,我有一些常見的驗證我想在任何URL字段進行(例如,檢查了域是允許的)。將這個通用驗證代碼分解爲單獨的函數而不是在每個驗證閉包中放入同一個塊的語法是什麼?

回答

0

你是否試圖從幾個特質繼承(或者說讓我們實現)你的命令?

Trait CancelComponentCommand { 
    String cancelUrl 

    static constraints = { 
     cancelUrl validator: { url, obj -> 
      //some specific validation 
      //some common url validation 
     } 
    } 
} 

Trait RedirectComponenCommand { 
    String redirectUrl 

    static constraints = { 
      redirectUrl validator: { url, obj -> 
      //some specific validation 
      //some common url validation 
     } 
    } 
} 

@Validateable 
class MyCommand implements CancelComponentCommand, RedirectComponenCommand { 

} 

PS無需設置nullable: false,默認爲false。如果使用camelCase編寫字段,代碼更易讀。

+1

感謝您的提示! –