Last active
May 18, 2021 15:02
-
-
Save ppazos/a313a2789647690243291bf91ae3390d to your computer and use it in GitHub Desktop.
Groovy Code Generator Sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Spec { | |
def classes = [] | |
def model(args) | |
{ | |
def clazz = new Clazz().named(args.clazz) | |
if (args.withAttributes) | |
{ | |
clazz.attributes(args.withAttributes) | |
} | |
this.classes << clazz | |
return this | |
} | |
def generate() | |
{ | |
def code = "" | |
classes.each { clazz -> | |
code += "class ${clazz.name} {\n" | |
clazz.attributes.each { attr -> | |
code += " def ${attr}\n" | |
} | |
code += "}" | |
code += "\n" | |
} | |
return code | |
} | |
} | |
class Clazz { | |
def name | |
def attributes = [] | |
def named(name) | |
{ | |
this.name = name | |
return this | |
} | |
def attributes(attributes) | |
{ | |
this.attributes = attributes | |
} | |
} | |
def spec = new Spec() | |
def named = { name -> | |
return name | |
} | |
spec.model( clazz: named("Person"), withAttributes:["name", "age"] ) | |
.model( clazz: named("Role") ) | |
.generate() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment