Monday, November 26, 2012

Grails dbconsole

A feature I have never used in Grails is the h2 web browser. A great way to see what the db structure and what the data looks like. This allows you to easily see the db structure your domain classes boil down to.

If you are running an application at
localhost:8080/appname
 You can browse to
localhost:8080/appname/dbconsole
For the JDBC URL use the setting from your DataSource.groovy in my case
jdbc:h2:mem:devDb
 And there we go all domain objects visible. Not only can you run sql queries but you can insert, modify, delete.


Tuesday, November 6, 2012

Using ExpandoMetaClass in unit tests

There is great power in the ExpandoMetaClass, particularly when doing unit tests.
I want to unit test a specific Domain but it uses a service (in this case springSecurityService.encodePassword()) in one of its methods (protected void encodePassword). Rather than have an integration test or mock out the whole service I can just override a method on the fly. This allows me to just test the logic I am interested in.

The code in my test looks like this.


    void setUp() {
        println "setUp()"
        User.metaClass.encodePassword = {->
            password
        }
       
        def user = new User(username: 'user', enabled: true, password: '123').save(flush: true)
        assert user
    }
What I have done is overridden the method encodePassword on the class User.

Domain event features

The Grails Domain class has some really nice event features in the afterUpdate, beforeUpdate.
What I wanted was if the domain.status was set to completed then domain.completedDate would be filled in with the current date. And if the domain.status was set to anything else, then domain.completedDate would be made null.
Was pretty easy to add this code to the domain


    def afterUpdate() {
        if (status == Status.COMPLETED) {
        if (completedDate)
        completedDate = new Date()
        } else {
        completedDate = null
        }
   }




Monday, November 5, 2012

Groovy Enums

Found a neat trick for matching a String back to its enum. For instance if we have the following enum

public enum Status {
INBOX { public String toString() {"Inbox"}},
NEXT { public String toString() {"Next Action"}},
SOMEDAY { public String toString() {"Someday"}} }
 So if you had a String and wanted to match the enum it is as easy as

def a = "Inbox" as Status