Skip to content

Instantly share code, notes, and snippets.

@eric1234
Created September 14, 2009 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eric1234/186842 to your computer and use it in GitHub Desktop.
Save eric1234/186842 to your computer and use it in GitHub Desktop.
Script Template: Import legacy CSV data into Rails 1.x, 2.x app
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require File.dirname(__FILE__) + '/../config/environment'
require 'csv'
# http://gist.github.com/184784
class CSV::Reader::WithHeader < CSV::Reader
def self.parse(str_or_readable, fs=',', &blk)
headers = nil
super str_or_readable, fs do |row|
if headers
blk.call Hash[*headers.zip(row).flatten]
else
headers = row
end
end
end
end
# http://gist.github.com/184842
def import(data, &blk)
return nil if data.blank?
blk = proc {|x| x} unless block_given?
blk[data]
end
ActiveRecord::Base.transaction do
CSV::Reader::WithHeader.parse(File.open(ARGV.first)) do |row|
# TODO: Actually create necessary objects
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment