Search

Dark theme | Light theme

May 25, 2010

Grails Goodness: Execute Code for Current Environment

In Grails we can use the Environment class to execute code for specific environments. The method executeForCurrentEnvironment() takes a closure with the different environments and the code to be executed. This provides an elegant way to execute different blocks of code depending on the current environment.

The following sample is a simple controller where we set the value of the result variable depending on the environment. Besides the default environments - development, test, production - we can define our own custom environments. In the controller we provide the custom environment myenv.

package environment

import grails.util.Environment

class ExecuteController {

    def index = { 
        def result
     
        Environment.executeForCurrentEnvironment {
            development {
                result = 'Running in DEV mode.'
            }
            production {
                result = 'Running in production mode.'
            }
            myenv {
                result = 'Running in custom "myenv" mode.'
            }
        }
    
        render result
    }
}

We we run the Grails application with $ grails run-app and go to the URL http://localhost:8080/app/execute, we get the following output: Running in DEV mode.. When we run $ grails -Dgrails.env=myenv run-app we get the following output in our browser: Running in custom "myenv" mode..