Wednesday, February 2, 2011

DRY Way to Read CSV File Into ActiveRecord Model

I've been looking for a DRY way to do this for a while.

    require "csv"

    file_path = "data/lunar-lander-1520turbo.csv"

    # define columns, symbols MUST be column names in module
    names = {}



    names[:lander_name] = names.length 
    names[:wing] = names.length 
    names[:wheel] = names.length 
    names[:wheel_base] = 95
    start = true

    CSV.open(file_path, 'r') do |row|
      if start # skip first row
        start = false
      else
        puts "Creating #{row[names[:lander_name]]}"
        m = MobileDevice.new
        names.each_key { |name| m[name] = row[names[name]] }
        m.save
      end
    end

No comments: