Grails Snippets

This is ongoing post to record different useful codes snippets related to Grails framework

1. Default and Shared Constraints.
It turns out you can specify default constraints that can be applied and shared in any Domain Class. For example, by default the ‘nullable’ constraint is set to ‘false’. If you wish change that,then updated conf/Config.groovy as follows:

grails.gorm.default.constraints = {
    '*'(nullable: false)
    noBlankSized(blank: fralse, size: 4..25)
}

The ‘*’ attaches the constraint to all property’ validations. The constraint ‘myShared’ can be references in any validation you choose as follows:

class User{
...
 static constraints = {
        favoriteDish shared: "noBlankSized"
    }
}

This way you able to share your own default validations while ability to reuse as you like

2. Suppor Handling Request params

A request parameter value can be converted to a specific type with method invocation:

params.long('book.id')

This takes book.id and converts it to long type. Grails supports other methods like byte(), long(), boolean(). Since Grails 2.0 also support for dates.

3. Access Domain class from Plugin
Say you developing plugin that needs to access domain class in the application.

String className = "com.foo.bar.MyDomainClass"
Class clazz = grailsApplication.getDomainClass(className).clazz
def findAnything = clazz.findByStuff(params.stuff)

If Domain class without package and name unique across all packages:

String className = "MyDomainClass"
Class clazz = grailsApplication.domainClasses.find { it.clazz.simpleName == className }.clazz
def findAThing = clazz.findByStuff(params.stuff)

This may not be best practices as we are coupling the plugin with particular applications, however,perhaps in some circumstance it necessary

4. Mocking Upload File feature with multipart/form-data

void testFileUpload(){
        def imgContentType = 'image/jpeg'
        def imgContentBytes = '123' as byte[]
...
        controller.metaClass.request = new MockMultipartHttpServletRequest()
        controller.request.addFile(
            new MockMultipartFile('image', 'myImage.jpg', imgContentType, imgContentBytes)
        )
...
        controller.save()
...
        assertEquals HttpServletResponse.SC_OK, controller.response.status
..
    }

Current Path from Request
To get current path from the current controller and action:

request.forwardURI

Leave a Reply

Your email address will not be published. Required fields are marked *