Using a static closure for a re-usable GORM validator constraint in Grails

I’ve been gradually working on building my Grails contacts model and this feature stood out as something I didn’t want to get buried in that post, as it’s something others may find useful.

The story started by me trying to replicate a data modelling concept from my Synon days, called Key Redirection (or shared keys in a simpler form).

To set the scene, I have the following entities in my domain model.

  • Country
  • Address
  • County
  • Locality
  • StateProvinceTerritory

Country is the parent of County, Locality and StateProvinceTerritory. (ie the last three have a static belongsTo = [country:Country] in them).

Now when I setup an Address, I want to make sure the same Country is assigned to County Locality and StateProvinceTerritory. This is the shared key/key redirect scenario.

It turns out a static closure came to my rescue and provided a rather elegant solution. Thanks Burt Beckwith for imparting the critical nugget of information. :-) The closure has to be declared static too.

So here is my Address class with the resused closure.

Address

Here it is in it’s earlier guise, so you can see what refactoring accomplished.

Address 1-76

Address 77-115

Don’t you just love Groovy! :-) It rocks!

Advertisements

About this entry