This page has been converted from a dynamic Wordpress article to a static HTML document. As a result, some content may missing or not rendered correctly.

A Simple Grails Plugin ~ Fri, 06 Apr 2012 19:44:28 +0000

Before I get into this, I want to make it clear that my Groovy knowledge is basic to moderate, at best. Also, my Grails knowledge is even less. In fact, things like Grails rub me the wrong way. But I haven't seen any articles that clearly describe this process from a beginner's perspective. So this one is for the people getting exasperated with the abysmal documentation and search results.

Without further ado, let's write a simple Grails plugin that adds (and reads) its own configuration file, provides itself as a "bean" to the host Grails application, and is very simple to install and use. Our plugin is going to provide a simple object with some properties. We could provide a more complicated object, like a pooled database connection, using this same method. But for example's sake, we'll keep it simple. Here is the code for the object that will be provided by our plugin:

  package com.jrfom

  import grails.util.Environment

  class SpiffyObject {
    def foo
    def answer

    SpiffyObject() {
      def config = {}
      GroovyClassLoader classLoader = new GroovyClassLoader(getClass().getClassLoader())
      Environment env = Environment.getCurrent()
      String envName = env.getName()

      try {
        config = new ConfigSlurper(envName).parse(classLoader.loadClass('SpiffyObjectConfig'))
      } catch (Exception e) {
        // Do something good here
      } =
      this.answer = config.answer

So, let's get started. First, we need to create our plugin and put our SpiffyObject in the correct location:

  $ cd ~/GrailsProjects/
  $ grails create-plugin spiffy-plugin
  $ cd spiffy-plugin
  $ mkdir -p src/groovy/com/jrfom
  $ touch src/groovy/com/jrfom/SpiffyObject.groovy # then open in your editor and paste in the code

Now we need to define our configuration file. This file will be added to the host Grails application's grails-app/conf/ directory when our spiffy-plugin is installed. So:

  $ mkdir -p src/samples
  $ touch src/sample/SpiffyObjectConfig.groovy # and open in your editor

Now paste in this bit of code:

  environments {
    development {
      foo = "baz"
      answer = 66

    test {
      foo = "bork"
      answer = 99

    production {
      foo = "bar"
      answer = 42

Next we need to add some code to Grails' special install script that gets run when a plugin is installed. So open scripts/_Install.groovy in your editor and add the following code to the end of the file:

  def configFile = new File('grails-app/conf/SpiffyObjectConfig.groovy')
  if (!configFile.exists()) {
      file: "${pluginBasedir}/src/samples/SpiffyObjectConfig.groovy",
      todir: "${basedir}/grails-app/conf")

The above code will check to see if the config file already exists in the application's config directory. If the config does not exist, it will copy our default configuration file (from src/samples) to the application's config directory. Otherwise, it will leave the current configuration alone.

Finally, we need to add the code that will define our bean when the Grails application is started. So open SpiffyObjectGrailsPlugin.groovy (found in the plugin's root directory) in your editor and adjust the doWithSpring method to look like:

  def doWithSpring = {
    // Define a bean for our plugin that can be used across the whole app
    spiffyObject(SpiffyObject) {}

Additionally, you will need to add an import to the top of the file. So, before the "class SpiffyObjectGrailsPlugin {" line, add "import com.jrfom.SpiffyObject".

You can now use the "grails package-plugin" command to package the plugin. Once you install the plugin into a Grails application, you can work with it like any other bean. For example, add the following code to grails-app/controllers/com/jrfom/SpiffyTestController.groovy:

  package com.jrfom

  import grails.converters.JSON

  class SpiffyTestController {
    def spiffyObject // indicate that we want to use the SpiffyObject bean

    def getAnswer = {
      def output = [:]

      output["answer"] = spiffyObject.answer

      render output as JSON

Now run your Grails app and then navigate to this service. Assuming your Grails app is named "spiffy" and is running on port 8080 on your local machine, you'd navigate to http://localhost:8080/spiffy/spiffyTest/getAnswer. Doing so should return a JSON formatted string that reads <code>{"answer":42}</code>.

It's definitely not intuitive, but that's all there is to creating an easy to use, unobtrusive, plugin that provides an application wide bean. Of course, you can do a lot more than this simple, mostly static, plugin by following these steps. Also, don't forget to modify the basic plugin properties in your SpiffyObjectGrailsPlugin.groovy file. These define the version number of your plugin, who wrote it, and its basic description. You should read over the official plugins documentation if none of this made any sense.

Code,  Grails,  Groovy,  Technology