0

I have a structured comma delimited file that has two record types. The different records are differentiated by a header entry: H or P. The file format follows:

"H","USA","MD","20904"
"P","1","A","Female","W"
"P","2","A","Male","H"

I'd like to import the file and then create activerecord models with the imported data. The approach that I am using is to create a field map that includes the number of fields, object name and columns.

I then utilize the field map

$field_map =

{
  'H'   =>
    {
      :count => 4,
      :object => :Header,
      :cols => [:record_type, :country_id, :state, :zip]
    },

  'R'   =>
    {
      :count => 4,
      :object => :RaceData,
      :cols => [:record_type, :household_size, :gender, :race]
    }
}

I then use FastCSV to import the file and use a case statement to how the file will be transformed and then used in activerecord create statements.

FasterCSV.foreach(filename) do |row|
    tbl_type = row[0]
    tbl_info = $field_map[tbl_type]

   unless (tbl_info.nil?)
     field_no = tbl_info[:count]
     object = tbl_info[:object]
     columns = tbl_info[:cols]
     record_type = new_record[:record_type]
     case record_type
         when "H"
         factory_build_h_record(new_record)
         when "P"
         factory_build_p_record(new_record)
     end
   end
 end

The code above is summarized due to space constraints. My approach works just fine, but my I'm new to ruby and I'm always interested in best practices and the "true" Ruby-way of doing things. I'd be interested in hearing how more experienced programmers would tackle this problem. Thanks for your input.

Mutuelinvestor
  • 3,384
  • 10
  • 44
  • 75

1 Answers1

0

I suggest the gem 'roo'

You have an example source code here but I rather watch the 10 min video

Helio Santos
  • 6,606
  • 3
  • 25
  • 31