【问题标题】:Groovy DSL: How I can overload any() in Groovy, when I create internal DSLGroovy DSL:当我创建内部 DSL 时,如何在 Groovy 中重载 any()
【发布时间】:2014-10-07 13:17:31
【问题描述】:

我创建了内部 DSL,我会从 DefaultGroovyMethods 重载 any() 方法。

class RulesProcessor {

}

Any live cell with fewer than two live neighbours dies

最后一行是我的 DSL。我尝试了 propertyMissing、methodMissing、创建我的 Any 类、RulesProcessor.metaClass.any、DefaultGroovyMethods.metaClass.any,但它们不起作用。

如何编写代码来接受我的 DSL?对我来说,只有“任何”字的第一步很复杂。

【问题讨论】:

    标签: groovy dsl


    【解决方案1】:

    如果您可以将其放入闭包中,只需将其委托给响应any 方法的对象,或者如我的示例中的invokeMethod

    class Dsl {
      def params = []
      def invokeMethod(String method, args) {
        params << [method, args]
        this
      }
    
      def propertyMissing(String prop) { prop }
    }
    
    
    a = {
      any live cell with fewer than two live neighbours dies
    }
    
    
    dsl = new Dsl()
    a.delegate = dsl
    a()
    
    assert dsl.params == [
      ['any',   ['live']],
      ['cell',  ['with']],
      ['fewer', ['than']],
      ['two',   ['live']],
      ['neighbours', ['dies']],
    ]
    

    如果您正在从文件中读取脚本,似乎有必要使用显式调用 any 的方法:

    import org.codehaus.groovy.control.CompilerConfiguration
    
    class Dsl {
      def params = []
      def invokeMethod(String method, args) {
        params << [method, args]
        this
      }
    
      def any(param) { invokeMethod('any', [param]) }
    
      def propertyMissing(String prop) { prop }
    }
    
    code = 'any live cell with fewer than two live neighbours dies'
    
    parsed = new GroovyShell(
        getClass().classLoader, 
        new Binding(), 
        new CompilerConfiguration(scriptBaseClass : DelegatingScript.class.name)
    ).parse( code )
    
    dsl = new Dsl()
    
    parsed.setDelegate( dsl )
    parsed.run()
    
    assert dsl.params == [
      ['any',   ['live']],
      ['cell',  ['with']],
      ['fewer', ['than']],
      ['two',   ['live']],
      ['neighbours', ['dies']],
    ]
    

    向 CompilerConfiguration 上的 mrhaki 致敬。

    【讨论】:

      猜你喜欢
      • 2012-07-10
      • 1970-01-01
      • 2018-05-22
      • 1970-01-01
      • 2019-04-06
      • 1970-01-01
      • 1970-01-01
      • 2012-07-14
      • 1970-01-01
      相关资源
      最近更新 更多