Sunday, May 3, 2009

Gradle to Framework idea

In order to support a project idea I am working on. I have come to the conclusion I will need component generation similar to what Rails or Grails has for their MVC components. I did, however, want to avoid creating this from the ground up.

This new framework has a couple technical requirements. The first is the generated code is going to be Groovy. The second is the component discovery should be by convention using directory and file names just like in those other frameworks. Out of curiosity I looked at Gradle to see if it might make things easier. And if it works out I would be getting a build system that is Groovy-centric automatically.

Up front I know I will have more than one component type to support. But first to prove the concept I start off with something that can create an Action component. To keep it flexible I will have a generate task that takes two properties, a component type and a component name. The task will then delegate to the appropriate groovy method to generate the right component.

Here is the build.gradle file:
// by convention actions will go into an actions folder
actionDirectory = new File("actions")

createTask('resources') {
actionDirectory.mkdirs()
}

// the main task that handles the component generation
createTask('generate', dependsOn: 'resources') {
if(componentType == "action") {
createAction(componentName)
println "Generating action ${componentName}"
} else {
println "Unknown component type - ${componentType} was given"
}
}

def createAction(componentName) {
// take the componentName and format it into an appropriate class name
def className = Character.toString(Character.toUpperCase(componentName.charAt(0))) + componentName.substring(1) + "Action"

println "Generating ${componentType} component class $className"

def actionFile = new File("actions/${className}.groovy")

actionFile.append("class $className { \n}")
}
With this I ran the command line:




The file is placed in the actions directory like so:



And it contains this simple bit of source:



That is it. The idea seems sound and it was pretty easy with Gradle supporting me. Obviously there will be plenty things to do to complete the project including some wrapper shell scripts to make it more command line friendly.