Reputation: 1442
I would to write a trait that several domain classes would share. For example I have two domain classes as such
class Comment{
String description
static hasMany = [replies: CommentReply]
String getFormattedDescription(){
// ...
return formattedDescription
}
}
class CommentReply{
String description
Comment comment
String getFormattedDescription(){
// ...
return formattedDescription
}
}
In this case, both Comment and CommentReply have same function getFormattedDescription() which can be moved to a trait and be implemented by the two domains classes. How can I achieve this?
How do I write traits that all domain classes would implement? For example GormEntity is implemented by all domains by default.
Upvotes: 2
Views: 436
Reputation: 27220
One way to do it is to write the trait and mark it with @Enhances('Domain')
.
import grails.artefact.Enhances
@Enhances('Domain')
trait YourTraitName {
// ...
}
That will add YourTraitName
to all domain classes.
In order for that to work you will need to configure the trait to be compiled in its own source set before your application code. A common way to manage that is to have the trait in a plugin (which could be part of a multi project build).
Upvotes: 1