Created
September 14, 2009 18:52
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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