通過「更新這些結構如果變化的過程」,你的意思改變讀取和寫入的CSV或YAML數據的代碼時,更改數據庫中的字段?
下面的代碼寫入和讀取的CSV任何AR對象/(需要FasterCSV寶石):
def load_from_csv(csv_filename, poro_class)
headers_read = []
first_record = true
num_headers = 0
transaction do
FCSV.foreach(csv_filename) do |row|
if first_record
headers_read = row
num_headers = headers_read.length
first_record = false
else
hash_values = {}
for col_index in 0...num_headers
hash_values[headers_read[col_index]] = row[col_index]
end
new_poro_obj = poro_class.new(hash_values) # assumes that your PORO has a constructor that accepts a hash. If not, you can do something like new_poro_obj.send(headers_read[col_index], row[col_index]) in the loop above
#work with your new_poro_obj
end
end
end
end
#objects is a list of ActiveRecord objects of the same class
def dump_to_csv(csv_filename, objects)
FCSV.open(csv_filename,'w') do |csv|
#get column names and write them as headers
col_names = objects[0].class.column_names()
csv << col_names
objects.each do |obj|
col_values = []
col_names.each do |col_name|
col_values.push obj[col_name]
end
csv << col_values
end
end
end
That's時,我說:「更新這些結構如果流程的變化」正是我的意思! 似乎這個代碼將任務變成一個毫不費力的任務! 非常感謝! – 2010-03-24 14:23:11