How to use a Groovy trait to output any class as csv?

The next example shows how to use a Trait to output a CSV string for any Class which implements the trait

trait TraitAsCSV {
   List<String> propertyNames() { { }.findAll { it != 'class'}
    String csvHeaders() {
    String asCSV() {
        def str = ""
        def arr = []
        for(def propName in propertyNames()) {
            def v = this."$propName"
            arr <<  (v ?: '')
    static String delimiter() {
class MeetupMember implements TraitAsCSV {
    String name
    String locality
    String twitter
    String facebook
    String tumblr
    String background
    String imageUrl
    String website         

The next Spock test will pass:

    def "test trait as csv works"() {

        def m = new MeetupMember() = 'Sergio del Amo'
        m.locality = 'Guadalajara'
        m.twitter = ''
        m.facebook = null
        m.tumblr = null
        m.imageUrl = '' = ''

        String csvHeaders = m.csvHeaders()

        csvHeaders == 'imageUrl;locality;twitter;tumblr;facebook;background;name;website'

        def csv = m.asCSV()

        csv == ";Guadalajara;;;;;Sergio del Amo;"

This Trait can be used for any class which you wish to output as a comma separated value. Useful to export information to be sued in Excel or to import it into another process.

Do you like to read about Groovy/Grails development? Yes, then Subscribe to Groovy Calamari a weekly curated email newsletter about the Groovy ecosystem which I write 

Leave a Reply

Your email address will not be published. Required fields are marked *