So we have unique 'codes' for some of our grails objects (ref data), and when we want to retrieve them, we do so by calling them with their static code:
Currency.findByCode(Currency.DOLLAR)
Perhaps I'm completely wrong, but this seems like a very verbose and non-groovy way of retrieving objects (especially when you have to do it multiple times, for multiple objects).
Is there a more accepted approach (maybe having a reference to the object itself somewhere)? If this is the best way to do it, that is an acceptable answer. Thanks.
One other thing that you could do to shorten up the code if you use static variables is to use static imports (this is actually part of Java, but I didn't find it till I moved to groovy):
If you do a static import of CurrencyType (potentially an enum holding the various types of Currency that you've defined) at the top of your class:
static import com.example.CurrencyType.*
Down in your code, you no longer need to prefix all of the references with CurrencyType
, you can just do:
Currency.findByCode(DOLLAR)
If they don't need to change, you could also add a helper method to your Currency class to retrieve it:
Currency.groovy:
static import com.example.CurrencyType.*
...
static transients = ['dollar']
...
static Currency getDollar() {
Currency.findByCode(DOLLAR)
}
That would let you use Currency.dollar
in your other code. In those classes, you could also use a static import there to just refer to dollar
:
static import com.example.Currency.*
....
println dollar // gets the dollar from the db and prints it out