2012-04-27 47 views
0

我正在创建一个mixin,添加到具有一些基本实用功能的控制器中。我想在mixin中执行的一项功能是使用g.message taglib解决错误。不幸的是,我似乎无法访问我的静态混合方法中的GrailsApplication如何访问Mixin中的GrailsApplication?

我如何从我的mixin访问Grails taglibs,还是有更好的方式来实现我正在做的 - 在所有控制器之间共享通用代码?

这是我正在运行的代码。我认为这个问题是如何访问Grails的标签库中的静态方法:

  static def preparePostResponse(domainInstance) { 

        def grailsApplication = new User().domainClass.grailsApplication 


        def postResponse = new AjaxPostResponse(domainObject: domainInstance) 

        if (domainInstance.hasErrors()) { 
         g.eachError(bean: domainInstance) { 
          postResponse.errors."${it.field}" = g.message(error: it) 
         } 
         postResponse.success = false 
         postResponse.message = "There was an error" 
        } 
        else { 
         postResponse.success = true 
         postResponse.message = "Success" 
        } 
        return postResponse 
       } 

回答

0

您可以从任何地方使用的几种技术之一您的应用程序访问grailsApplicationGrailsApplicationHolder已被弃用,但Burt Beckwith的couple of solutions in this blog posting

也许最简单的一种是将其拉出一个现有的域,像这样:

class MyMixin { 
    static myMethod() { 
     def grailsApplication = new MyDomainClass().domainClass.grailsApplication 
     // use it like normal here 
    } 
} 

他有另一种方法建立variables in BootStrap using metaClass here


或者,你可以使用更多的参与,但(我认为)更好的技术在this blog post创建一个专用类用于访问应用程序。这很好,如果你打算在几个地方使用它。我在我的应用程序有干将为grailsApplicationconfig等设立了专门AppCtx类很干净得多给它这样写:

def foo = AppCtx.grailsApplication... 
+0

我想你的建议,并grailsApplication是访问,但我开始空指针异常在groovy的肠子里。我认为这可能与在静态方法中使用g:tag,g:forEach有关。我把这个方法移到了控制器本身 - 仍然保持静态 - 并且得到了这个异常.'明显的变量'g'被发现在一个静态作用域中,但是并没有引用一个局部变量'。我可以从静态方法访问g:标签吗? – 2012-04-30 12:59:30