views:

780

answers:

2

I have the following Grails domain class:

class Product {  
    String name  
    Float basePrice  
    Category category  
    String image = "default.jpg"  

    static constraints = {
        name(size:3..25, blank:false)
        basePrice(scale:2, nullable:false)
        category(inList:Category.list(), nullable:false)
        image(blank:false)
    }
}

From a controller, I want to get the default value for the image property (in this case "default.jpg"). Something like this:

def productInstance = new Product(params)
productInstance.image = getProductPicturePath() ?: Product().image

getProductPicturePath returns an image path, but in case no image was submitted, the controller shall replace the null value with the default. While I could certainly write something like this:

productInstance.image = getProductPicturePath() ?: "default.jpg"

It's certainly not very DRY, and I would prefer to keep that default value in one place. How can I achieve this?

+4  A: 

the obvious solution is to declare it as a constant and then refer to it.

class Product {  
    static DEFAULT_IMAGE = "default.jpg"
    String name  
    Float basePrice  
    Category category  
    String image = DEFAULT_IMAGE

    static constraints = {
        name(size:3..25, blank:false)
        basePrice(scale:2, nullable:false)
        category(inList:Category.list(), nullable:false)
        image(blank:false)
    }

}

productInstance.image = getProductPicturePath() ?: Product.DEFAULT_IMAGE

Better still make getProductPicturePath() return the default value

Gareth Davis
Thanks, that's what I was looking for exactly.
Cesar
A: 

If there is no image key in params

def productInstance = new Product(params)

will skip this property and leave the default value defined in the domain class. So, assuming that your params doesn't contain an image key, the simplest way would be to skip the assignment of the image property at all for those products that have no image:

def imagePath = getProductPicturePath()
if(imagePath) {
    productInstance.image = imagePath
}
Daniel Rinser
I was not aware of that. My params contains an image key, it comes from a upload form with other fields and the user may or may not upload an image file.
Cesar