0

我正在开发一个插件,getFlashHelper为每个控制器添加一个方法。这个方法应该返回一个FlashHelper类的实例。

但是,FlashHelper类的构造函数必须传递调用该​​方法的控制器的实例。getFlashHelper

希望下面的代码能更好地解释我正在做的事情

def doWithDynamicMethods = {ctx ->

    application.controllerClasses*.metaClass*.getFlashHelper = {

        def controllerInstance = delegate

        // Avoid creating a new FlashHelper each time the 'flashHelper' property is accessed
        if (!controllerInstance.metaClass.hasProperty('flashHelperInstance')) {
            controllerInstance.metaClass.flashHelperInstance = new FlashHelper(controller: controllerInstance)
        }

        // Return the FlashHelper instance. There may be a simpler way, but I tried
        // controllerInstance.metaClass.getMetaProperty('flashHelperInstance')
        // and it didn't work
        return controllerInstance.metaClass.getMetaProperty('flashHelperInstance').getter.invoke(controllerInstance, [] as Object[])
    }
}

该代码似乎可以工作,但我不禁感到必须有一种更简单的方法来做到这一点。最后一行特别令人毛骨悚然。有什么办法可以简化这个吗?

谢谢,唐

4

1 回答 1

1

由于控制器是按请求创建的,因此我将帮助程序存储为请求属性:

for (c in grailsApplication.controllerClasses) {
   c.clazz.metaClass.getFlashHelper = { ->
      def controllerInstance = delegate
      def request = controllerInstance.request
      def helper = request['__flash_helper__']
      if (!helper) {
         helper = new FlashHelper(controller: controllerInstance)
         request['__flash_helper__'] = helper
      }
      helper
   }
}
于 2010-01-28T02:37:04.487 回答