rubycsvfastercsv

Is there a Ruby CSV parser that generates column getter methods?


I'm trying to generalize a data retrieval mechanism with Ruby, and can't seem to find a way to retrieve a CSV file and access one of the row's columns by using a dot operator like so:

Let's say I have a CSV table:

#some_file.csv
name,age
albert,13

And I create a FasterCSV table from it:

a = FasterCSV.new(File.open('some_file.csv'), :headers => :first_row)

Then, when accessing a row, I'd like to be able to say:

a[0].name
=> 'albert'

Instead of

a[0]['name']
=> 'albert'

Anyone know how to do that?


Solution

  • Well, if you don't find one, you can always monkey-patch FasterCSV::Row class, something like:

    class FasterCSV::Row
      def method_missing(m,*args)
        if self.field?(m.to_s)
          return self[m.to_s]
        else
          super
        end
      end
    end
    

    (Haven't tried the code myself.)

    PS. As you are generalizing data retrieval mechanism, I assume that CSV is just one of several data sources you plan to support. The logical thing then would be to create a single wrapper class for each of your data sources, with some common interface (which might or might not use accessors for accessing row fields). But underneath it should still access CSV row usual way, using [] method. So, as Glenjamin already asked, why do you need this at all? ;)