Groovy&Grails-代码剪辑-复用约束

假如咱们在程序中使用了一个command对象,在Grails2.0以后的版本中引入了新的机制,能够复用constraints块的代码,重用约束,以下面的例子:正则表达式

<!-- lang: groovy -->
class User {
    String firstName
    String lastName
    String passwordHash

    static constraints = { 
        firstName blank: false, nullable: false 
        lastName blank: false, nullable: false 
        passwordHash blank: false, nullable: false 
    } 
}

上面的代码时一个标准的domain对象,假如咱们要在页面中增长一个密码验证,经常使用的办法是增长一个相似的command对象,代码以下:dom

<!-- lang: groovy -->
class UserCommand {
    String firstName
    String lastName
    String password
    String confirmPassword

    static constraints = { 
        importFrom User
        password blank: false, nullable: false 
        confirmPassword blank: false, nullable: false 
    } 
}

上面的代码修改了password为没加密的密码,新增长了一个confirmPassword属性,其余的和domain对象同样,包括约束也应该同样,因此这里能够使用importFrom User重用User的约束加密

若是不须要彻底使用User的约束,能够使用include和exclude参数,include代码指定引入,exclude表明排除,以下:code

<!-- lang: groovy -->
…
static constraints = {
    importFrom User, include: ["lastName"]
    …
}

上面的代码表示只引入lastName的约束信息对象

<!-- lang: groovy -->
…
static constraints = {
    importFrom User, include: [/.*Name/]
    …
}

上面的代码表示只引入后缀为Name的属性的约束信息,这里还使用了正则表达式。若是使用exclude则反之ast