Saturday, 19 February 2011

Grails Tip: Accessing a Service from a Plain Old Groovy Object

Here's an example of how to access a Grails Service from a POGO:

package com.questern.aoms.pogo

import com.questern.aoms.MaterialDetail
import org.codehaus.groovy.grails.commons.ApplicationHolder as AH

class MaterialRow {
    Long id
    Integer layerNo
    String type
    String colour
    Double thickness
    String units

    def ctx = AH.application.mainContext
    def refCodeService = ctx.refCodeService

    public MaterialRow(){}

    public MaterialRow(MaterialDetail detail){
        this.id = detail.id
        this.layerNo = detail.layerNo
        this.type = detail.type
        this.colour = detail.colour
        this.thickness = detail.thickness

        def refCodeInstance = refCodeService.get("Material", this.type)
        def form = refCodeInstance?.meaning
        if(form == "Paper"){
            this.units = "gr"
        } else {
            this.units = "mu"
        }
    }
}