views:

370

answers:

2

I need to call the Static Resources Plugin (http://www.grails.org/Static+Resources+Plugin) from my domain class.

This works perfectly in a controller:

 def tstLink = resourceLinkTo(dir:"docs/${identifier}",file:originalFileName)

but in a domain class I get

Exception Message: No signature of method: static org.maflt.ibidem.Item.resourceLinkTo() is applicable for argument types: (java.util.LinkedHashMap) values: [[dir:docs/19e9ea9d-5fae-4a35-80a2-daedfbc7c2c2, file:2009-11-12_1552.png]] 

I assume this is a general problem.

So how do you call a taglib as a function in a domain class?

A: 

Most taglibs rely on data from the controller so it's often not possible to reuse them while others concern view logic so often it's not something you would want to put in a domain class.

That said, I'm sure you have your reasons so maybe the source of the taglib will help:

class ResourceTagLib  {

    def externalResourceServerService

    def resourceLinkTo = { attrs ->
        out << externalResourceServerService.uri
        out << '/'
        if(attrs['dir']) {
            out << "${attrs['dir']}/"
        }
        if(attrs['file']) {
            out << "${attrs['file']}"
        }
    }
}

ie inject the externalResourceServerService into your domain class and the rest should be simple.

Dave
Thanks.I would have expected that to work too. I did def tstLink = externalResourceServerService.resourceLinkTo(dir:"docs/${identifier}",file:originalFileName)but got No signature of method: ExternalResourceServerService.resourceLinkTo() is applicable for argument types: (java.util.LinkedHashMap) values: [[dir:docs/279a5b71-b05f-4d62-be7b-72a805b005e0, file:me.jpeg]]
Brad Rhoads
So it seems like I just need to get the data types correct. This doesn't work either def tstLink2 = externalResourceServerService.resourceLinkTo ("docs/${identifier}".toString(),originalFileName) with or without the toString().
Brad Rhoads
+3  A: 

I encountered this problem a while ago for an app I was working on. What I ended up doing was putting a call to the tag in a service method:

class MyService {
   def grailsApplication //autowired by spring

   def methodThatUsesATag(identifier, originalFileName) {
      //This is the default grails tag library
      def g = grailsApplication.mainContext.getBean('org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib')

      g.resourceLinkTo(dir:"docs/${identifier}",file:originalFileName)
   }
}

Then in my domain class, I could get to the service via spring autowiring as well:

class MyDomain {
    String originalFileName
    def myService  //autowired

    static transients = ['myService'] //Necessary so that GORM doesn't try to persist the service instance.

    //You can create a method at this point that uses your
    //service to return what you need from the domain instance.
    def myMethod() {
       myService.methodThatUsesATag(id, originalFileName)
    }
}
Matt Lachman