Skip to content

Bootstrapping, An Environmentalist’s Perspective

September 28, 2009

Grails gives you a handy little class called Bootstrap.groovy.  As it’s name implies this class allows you to “bootstrap” your application at startup (and shutdown).  This is pretty handy in development when you want your application to start with some sample data loaded.  For example, you might use Bootstrap.groovy to create a bunch of test user accounts (that’s what we do for Sierra).  As you start to move your application into production you might find yourself commenting out lines of code (I did) in Bootstrap.groovy so that the production version of your application does not launch with all of your sample data loaded.

This week as I was working on some administrative functions for Sierra I found myself thinking there had to be a better way, and it turns out there is.  As I’ve discussed before when Grails launches it knows what mode/environment it’s running in.  The default environments are “development”, “test”, and “production”.  The Grails configuration scripts Config.groovy, DataSource.groovy, etc… give you handy “environments” blocks, but what about classes such as Bootstrap.groovy.  What should we do there?  The answer is the grails.util.Environment class.  This class knows what the current running environment is.  If we use this in Bootstrap.groovy we now have a way to only load our sample data if we are in “development” mode.  This is how it looks:

if (Environment.getCurrent() == Environment.DEVELOPMENT) {

// Insert sample data here

}

Advertisement
No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.