Advertisement
Guest User

Untitled

a guest
Sep 26th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. import org.codehaus.groovy.control.CompilerConfiguration
  2. import org.codehaus.groovy.runtime.InvokerHelper
  3.  
  4. class Bar {
  5. String bar
  6.  
  7. void bar(String bar) {
  8. this.bar = bar
  9. }
  10. }
  11.  
  12. class Foo {
  13. Bar bar
  14.  
  15. void foo(@DelegatesTo(value = Bar, strategy = Closure.DELEGATE_FIRST) closure) {
  16. def bar = new Bar()
  17. def code = closure.rehydrate(bar, this, this)
  18. code()
  19. this.bar = bar
  20. }
  21. }
  22.  
  23. abstract class MyScript extends Script {
  24.  
  25. Foo dslEntryPoint(@DelegatesTo(value = Foo, strategy = Closure.DELEGATE_FIRST) closure) {
  26. def foo = new Foo()
  27. def code = closure.rehydrate(foo, this, this)
  28. code()
  29. foo
  30. }
  31. }
  32.  
  33. def DSL_NOT_OK = """
  34. dslEntryPoint() {
  35. foo {
  36. bar magicValue
  37. }
  38. }
  39. """
  40.  
  41. def DSL_OK = """
  42. def myMagicValue = magicValue
  43. dslEntryPoint() {
  44. foo {
  45. bar myMagicValue
  46. }
  47. }
  48. """
  49.  
  50. CompilerConfiguration config = new CompilerConfiguration(CompilerConfiguration.DEFAULT)
  51. config.scriptBaseClass = MyScript.class.name
  52. GroovyClassLoader groovyClassLoader = new GroovyClassLoader(getClass().getClassLoader(), config)
  53. Class<Script> clazz = groovyClassLoader.parseClass(DSL_NOT_OK)
  54. Binding binding = new Binding()
  55. binding.setVariable('magicValue', '42')
  56. Script script = InvokerHelper.createScript(clazz, binding)
  57. Foo foo = script.run() as Foo
  58. assert foo.bar.bar == '42'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement