Search code examples
grailsgroovygrails-orm

How to abstract out datasource selection in a DRYish way using GORM


I have a domain set up with n datasources (we will call it 2 here). I currently have to access the objects for finds etc this way...

// DS1
Item.find(id)
// DS2
Item.ds2.find(id);

This works ok on a small logical function but when there are a alot of finds and saves it makes a very un-DRY environment...

if(isDs1){
  Item.find(id)
  ...
}
else{
  Item.ds.find(id)
  ...
}

I was thinking something like this in JS...

String ds = isDs1 ? 'ds1' : 'ds2'
Item[ds].find(id)

But this isn't possible in Groovy(?)

This there another way to do this in a fairly DRY way?

Update

for those that are confused my DataSource.groovy would look like this...

environments {
  development {
    datasource_ds1{
      ...
    }
    datasource_ds2{
      ...
    }
  }
}

Solution

  • Groovy has support for dynamic invocation. The equivalent to your javascript example would be something like this:

    String ds = isDs1 ? 'ds1' : 'ds2'
    Item."${ds}".find(id)