Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy DSL: How I can overload any() in Groovy, when I create internal DSL

Tags:

groovy

dsl

I create Internal DSL and I would overload any() method from DefaultGroovyMethods.

class RulesProcessor {

}

Any live cell with fewer than two live neighbours dies

The last line is my DSL. I tried propertyMissing, methodMissing, create my Any class, RulesProcessor.metaClass.any, DefaultGroovyMethods.metaClass.any, but they doesn't work.

How I can write code to accept my DSL? Only first step with 'Any' word is complicated for me.

like image 937
Marcin Stachniuk Avatar asked Jan 25 '26 18:01

Marcin Stachniuk


1 Answers

If you can put it in a closure, just delegate it to an object which responds to any method or, as in my example, 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']],
]

If you are reading the script from a file, having a method explicitly called any seems necessary:

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']],
]

Kudos to mrhaki on CompilerConfiguration.

like image 117
Will Avatar answered Jan 28 '26 07:01

Will



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!