2017-04-18 4 views
1

하자 나는 다음과 같은 명령이 말하는 :그루비 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

몇 가지 특성에서 명령을 상속 (또는 구현한다고 가정) 했습니까? nullable: false를 설정할 필요가 없습니다

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, 그것은 기본적으로 false입니다. 또한 필드가 camelCase를 사용하여 작성된 경우 코드가 훨씬 더 읽기 쉽습니다.

+1

팁 주셔서 감사합니다! –