Created
May 4, 2010 00:46
-
-
Save nateware/388799 to your computer and use it in GitHub Desktop.
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
# Ruby 1.9 compat for FasterCSV (painful) | |
# http://matthewbass.com/2008/01/05/csv-transmogrifies-into-fastercsv-in-ruby-19/ | |
require 'csv' | |
if CSV.const_defined? :Reader | |
require 'faster_csv' # For CSV data files | |
else | |
FasterCSV = CSV | |
end | |
namespace :db do | |
# Adapted from http://erikonrails.snowedin.net/?p=212 | |
desc "Load all data from CSV files in RAILS_ROOT/db/seed_data" | |
task :load_data => :environment do | |
Dir["#{RAILS_ROOT}/db/seed_data/*.csv"].each do |f| | |
# remove numeric ordering | |
table_name = File.basename(f, '.csv').sub(/^\d+_?/,'') | |
# and _by_column_name which uses is configuration | |
unique_key = table_name.gsub!(/_by_(\w+)/,'') ? $1.to_s : nil | |
model_class = table_name.to_s.singularize.camelize.constantize | |
pk_name = model_class.primary_key # maybe 'id' or 'code' or ?? | |
unique_key ||= pk_name | |
# puts "primary_key(#{model_class}) = #{pk_name}" | |
puts "-- loading data for #{table_name} from: #{f.sub(/.*(db\/)/,'\1')}" | |
csv_rows = FasterCSV.read(f, :headers => true, :header_converters => :downcase) | |
csv_rows.each do |row| | |
attrib = row.to_hash | |
pk_val = attrib[unique_key] || raise("CSV entry missing value for #{unique_key}: #{row}") | |
record = model_class.find(pk_val) rescue nil | |
if record | |
# update | |
attrib[:updated_at] = Time.now if record.respond_to?(:updated_at) | |
record.update_attributes!(attrib) | |
else | |
record = model_class.new(attrib) # get new AR object | |
# Use send to call pk attribute setter, eg, admin_account.id= or language.code= | |
# These are protected in ActiveRecord so you must send() to them | |
record.send("#{pk_name}=", pk_val) if pk_val | |
record.created_at = Time.now if record.respond_to?(:created_at) | |
record.updated_at = Time.now if record.respond_to?(:updated_at) | |
record.save! | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment