Class: SodaCSV

Inherits:
Object
  • Object
show all
Defined in:
lib/SodaCSV.rb

Overview

SodaCSV – Class

This class parses CSV files and converts them into records that can be 
accessed as variables in Soda XML scripts.  The first ROW of CSV file is
the variable names to be used Then each subsequent ROW is data.

Params:

file: This the csv file.

Results:

None.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file) ⇒ SodaCSV

Returns a new instance of SodaCSV.



49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/SodaCSV.rb', line 49

def initialize(file)
   @csvdata = CSV.open(file, 'r')
   @fieldMap = @csvdata.shift
        len = @fieldMap.length() -1

   # this is to deal with badly writen CSV files #
   for i in 0..len do
      if (@fieldMap[i] == nil)
         @fieldMap[i] = ""
      end
   end
end

Instance Attribute Details

#csvdataObject

Returns the value of attribute csvdata.



47
48
49
# File 'lib/SodaCSV.rb', line 47

def csvdata
  @csvdata
end

#fieldMapObject

Returns the value of attribute fieldMap.



47
48
49
# File 'lib/SodaCSV.rb', line 47

def fieldMap
  @fieldMap
end

Instance Method Details

#nextRecordObject

nextRecord – Method

This method pulls the next record from the CSV and returns it as a hash.

Params:

None.

Results:

returns a filled hash on success, or nil on error or no data.


73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/SodaCSV.rb', line 73

def nextRecord()
   record = {}
   data = @csvdata.shift
   all_nil = true

   if (!data.empty?)
      @fieldMap.each_index do|k|
         if (!data[k].to_s.empty?)
            all_nil = false
         end

         if (data[k] != nil)
            data[k] = data[k].gsub('\n', "\n")
         else
            data[k] = ""
         end

         record[@fieldMap[k]] = data[k]
      end
   else 
      record = nil
   end

   if ( (all_nil != false) || (record == nil) )
      record = nil
   end

   return record
end