1

The next piece of Groovy code works in Grails (thanks @Will P) for your answer:

String string2code = "variable = 'hello'; return variable.toUpperCase()";

def result = new GroovyShell().evaluate string2code
assert result == "HELLO"

Unfortunately, if we introduce the magic querying of Grails, it fails:

String string2code = "return DomainClassExample.findByName('hello')";
// String string2code = "DomainClassExample.where { name == 'hello' }"
def queryResult = new GroovyShell().evaluate string2code

This is the error:

Class
    groovy.lang.MissingPropertyException
Message
    No such property: DomainClassExample for class: Script1

Is it possible? How?

Community
  • 1
  • 1
chelder
  • 3,819
  • 6
  • 56
  • 90

1 Answers1

2

The classloader used by the GroovyShell doesn't know about the Grails artifact classes that are loaded at runtime. But if you pass in the Grails classloader as its parent classloader, the classes will resolve. Grails registers its classloader as the thread's context classloader, so this is a quick way of doing what you want:

def queryResult = new GroovyShell(Thread.currentThread().contextClassLoader).evaluate string2code
Burt Beckwith
  • 75,342
  • 5
  • 143
  • 156
  • 1
    A corollary to this is that what you initially tried _will_ work in a deployed WAR or `grails run-war` (where artifacts are in the same classloader as the Groovy runtime itself), but not in `run-app`. – Ian Roberts Jul 05 '13 at 15:10
  • Thank you! I don't understand what do you mean with "run-app" though. I thought the only way to run the app is writting "grails run-app" (in Eclipse run As - Grails application which I think it's the same that "grails run-app) – chelder Jul 05 '13 at 16:58