Grails, storing app own settings (singleton domain class?)

I'm developing an app using Grails and there are some app-wide configuration settings I'd like to store somewhere. The only way I've thought of is to create a domain class that stores the configuration values, and to use a service that queries that domain class. The problem I see is that there should be just one instance of that domain class, but I haven't found anything to enforce that restriction.

There may be other best practices to store app's own configuration that I may not be aware of, all suggestions are welcome.

Edit: the settings are supposed to be configurable from within the app.

Upvotes: 2

Views: 2027

Answers (4)

Anatoly
Anatoly

Reputation: 456

You can enforce your single domain class db entry via custom validator:

// No more than one entry in DB
class MasterAccount {
    boolean singleEntry = true
    static constraints = {
         singleEntry nullable: false, validator: { val, obj ->
              if(val && obj.id != getMasterAccount()?.id && MasterAccount.count > 0){
                    return "Master account already exists in database"
              }
         }
    }
    MasterAccount static getMasterAccount(){
         MasterAccount.list()?.first()
    }
}

You can defer its configuration and persistence to Bootstrap.groovy, which would achieve the same effect as Config.groovy

Upvotes: 2

Roberto Perez Alcolea
Roberto Perez Alcolea

Reputation: 1414

If you're using 1.3.* you can try grails dynamic-config plugin (http://www.grails.org/plugin/dynamic-config). "This plugin gives your application the ability to change the config properties without restarting the application. The values in Config.groovy are persisted in database when application is run-for the first time after installing the plugin. "

I've never used it on a grails 2.0.* project.

Upvotes: 0

Kelly
Kelly

Reputation: 3709

There is a plugin for that: Settings. It allows you to create named setting like my.own.x of different types (String, date, BigDecimal and integer), and provides you with the basic CRUD pages to manage them.

You can access the settings from either gsp:

<g:setting valueFor="my.own.x" default="50" encodeAs="HTML"/> 

or controllers/services/domains

Setting.valueFor("my.own.x", 50)

I use it in several projects and think it works great.

Upvotes: 5

Igor Artamonov
Igor Artamonov

Reputation: 35961

There is special place: /grails-app/conf/Config.groovy. You can add values there like:

my.own.x=1

and read values by:

def x = grailsApplication.config.my.own.x

See docs for more details: http://grails.org/doc/latest/guide/conf.html#config

Upvotes: 7

Related Questions