2013-08-25 19 views
1
class User { 
    static constraints = { 
     password(unique:true, length:5..15, validator:{val, obj -> 
      if(val?.equalsIgnoreCase(obj.firstName)) { 
       return false 
      } 
     } 
    } 
} 

我發現這個groovy語法真令人費解。我花了幾天的時間來學習Grails/Groovy。我知道它做了什麼,但我並不真正瞭解它。Grails域的類的語法解釋

有人可以解釋這是如何工作的?

什麼是約束?它是一個關閉,密碼被稱爲一個函數? 它是如何被調用的?

驗證程序怎麼樣的語法呢?

就像我說的,我可以看到它做了什麼,我只是不明白它是如何做到的。

回答

2

前言 - 有些部分需要Groovy使用的基本知識。

//Domain Class 
class User { 
    //A property of the domain class 
    //corresponding to a column in the table User. 
    String password 

    //Domain classes and Command objects are treated specially in Grails 
    //where they have the flexibility of validating the properties 
    //based on the constraints levied on them. 
    //Similar functionality can be achieved by a POGO class 
    //if it uses @Validateable transformation at the class level. 
    static constraints = { 
     //Constraints is a closure where validation of domain class 
     //properties are set which can be validated against when the domain class 
     //is saved or validate() is called explicitly. 
     //This is driven by AbstractConstraint and Constraint java class 
     //from grails-core 

     //Constraint on password field is set below. 
     //Here password is not treated as a method call 
     //but used to set the parameter name in the constraint class on which 
     //validation will be applied against. Refer AbstractConstraint 
     //for the same. 
     password(unique:true, size:5..15, validator:{val, obj -> 
      //Each of the key in the above map represents a constraint class 
      //by itself 
      //For example: size > SizeConstraint; validator > ValidatorConstraint 
      if(val?.equalsIgnoreCase(obj.firstName)) { 
       return false 
      } 
     } 
    } 
} 

上面提到的是約束如何工作的基礎知識。如果您需要了解更多的詳細信息,然後這裏有一些你絕對需要的,如果你得到關於它的使用任何進一步的問題訪問來源:

鄂畢虛擬地說,如果你被困在與約束有關的任何實現中,SO是提問的好地方。隨意使用這個社區來幫助你克服有問題的程序化情況。

+0

所以我得到這就是密碼的作用,但如果它不是一個方法調用它是什麼?通過什麼神奇的工作。什麼是「val?」意思?我從來沒有見過這種語法,我正在閱讀的書不能解釋它 –

+2

Grails中有很多魔術。我想當你剛剛開始時,最好接受它。一旦你對框架有了更好的瞭解,我建議你給Burt Beckwith編寫一份Grails編程(http://shop.oreilly.com/product/0636920024750.do)。它進一步解釋了大多數Grails書籍的內幕。 – rcgeorge23

+0

好吧,我想我現在已經想出了這個東西... val ?.基本上是val的nullsafe版本。對?並且驗證者val,obj之後的第一位是函數變量? –