Groovy can i dynamically execute a string as groovy command? Groovy can i dynamically execute a string as groovy command? database database

Groovy can i dynamically execute a string as groovy command?


If you have some Groovy code in a String you can use the Eval class to execute it. Here's a simple example you can try out in the Groovy console:

def code = "2 + 2"assert Eval.me(code) == 4


Groovy can be concise and expressive, so you can quickly jump into the scripts to read or make changes, which means you might be able to just put your code into the scripts instead of into the database -- this is why you often see configurations done in code instead of properties or databases.

Anyway...

GroovyShell will allow you to evaluate any String you build as code, so you could write code to build one big string from your database, then pass it to GroovyShell.evaluate(String) to execute it.

Here's a sample:

#!/usr/bin/env groovynew GroovyShell().evaluate("""    @Grapes([        @Grab("org.codehaus.geb:geb-core:0.6.0"),        @Grab("org.seleniumhq.selenium:selenium-htmlunit-driver:2.0rc3")    ])    import geb.Browser    Browser.drive {        go "http://www.test.com/"        $("form", name: "password").value("Test")    }""")

More simply, you could skip using GroovyShell within your own scripts and write the bit of code that reads the DB and generates the code and have it just dump the code to a file, then execute the new file any time you want. That file can serve as a sort of snapshot of what really got executed.