Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.codehaus.groovy.control.CompilerConfiguration
- import org.codehaus.groovy.runtime.InvokerHelper
- class Bar {
- String bar
- void bar(String bar) {
- this.bar = bar
- }
- }
- class Foo {
- Bar bar
- void foo(@DelegatesTo(value = Bar, strategy = Closure.DELEGATE_FIRST) closure) {
- def bar = new Bar()
- def code = closure.rehydrate(bar, this, this)
- code()
- this.bar = bar
- }
- }
- abstract class MyScript extends Script {
- Foo dslEntryPoint(@DelegatesTo(value = Foo, strategy = Closure.DELEGATE_FIRST) closure) {
- def foo = new Foo()
- def code = closure.rehydrate(foo, this, this)
- code()
- foo
- }
- }
- def DSL_NOT_OK = """
- dslEntryPoint() {
- foo {
- bar magicValue
- }
- }
- """
- def DSL_OK = """
- def myMagicValue = magicValue
- dslEntryPoint() {
- foo {
- bar myMagicValue
- }
- }
- """
- CompilerConfiguration config = new CompilerConfiguration(CompilerConfiguration.DEFAULT)
- config.scriptBaseClass = MyScript.class.name
- GroovyClassLoader groovyClassLoader = new GroovyClassLoader(getClass().getClassLoader(), config)
- Class<Script> clazz = groovyClassLoader.parseClass(DSL_NOT_OK)
- Binding binding = new Binding()
- binding.setVariable('magicValue', '42')
- Script script = InvokerHelper.createScript(clazz, binding)
- Foo foo = script.run() as Foo
- assert foo.bar.bar == '42'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement