user1432980 user1432980 - 3 months ago 13
Groovy Question

evaluate script against object

I had script inside text file

application.txt


application {
title "Template application"
settings {}
}


I evaluated it like this

def application = new MainForm()
Binding binding = new Binding()
binding.setVariable("application", application)

GroovyShell shell = new GroovyShell(binding)
evaluate(new File("application.txt"))


where my
MainForm
object contains code like this

class MainForm {

def call(Closure cl) {
cl.delegate = this
cl()
}

def methodMissing(String name, args) {
if (name == "title") {
....
} else {
....
}
}
}


But I decided to get rid of unessesary
application {}
facility inside text file and leave just plain

title "Template application"
settings {}


The code I used does not work anymore, throwing me
missing method
exception.

def application = new MainForm()
Binding binding = new Binding()
binding.setVariable("application", application)

GroovyShell shell = new GroovyShell(binding)
evaluate(new File("application.txt"))


How should I change this code in order to make my new approach working? (basically I want to evaluate code as it was in the instance of
application
)

Answer

The only solution I found is like this

http://jorgemanrubia.com/2009/10/10/evaluating-code-dynamically-in-groovy/

with wrapping new File().text into a closure and then delegating it to object