Loading...

Tuesday, 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..

3 comments:

Andres Almiray said...

The same trick can be applied in Griffon, in case you're wondering ;-)

mrhaki said...

@Andres Almiray: ;-) of course I could have guessed. Haha. But when I tried I couldn't get my custom environment to work. Maybe has to do with methodMissing(String name, Object[] args) vs. methodMissing(String name, Object args). Latter is in Grails codebase, first in Griffon codebase.

rsilva said...

Hi mrhaki, is there a else branch we can specify?:

Environment.executeForCurrentEnvironment {
development {
result = 'mock some authentication'
}
default { //or production, myenv{
result = 'use good and strong authentication'
}
}

render result

My objective is avoid repetition of the same behavior for different environments.

At the momento I'm using this:

if(Environment.current == Environment.DEVELOPMENT)
return true
else{
...
}

Post a Comment