2010-03-24 56 views
0

我正在開發一個「腳本生成器」來自動化工作中的一些進程。 它有一個運行在服務器上的Rails應用程序,該應用程序存儲製作該腳本所需的所有數據,並在該過程結束時生成腳本本身。將ActiveRecord對象導出到POROs

我遇到的問題是如何將數據從ActiveRecord格式導出爲普通舊式Ruby對象(PO​​RO),以便我可以在沒有數據庫支持和純紅寶石實現的腳本中處理它們。

我想過YAML,CSV或像這樣導出的數據,但是這將是一個痛苦的過程,如果過程中的變化來更新這些結構。有一種更簡單的方法嗎?

Ty!

回答

2

通過「更新這些結構如果變化的過程」,你的意思改變讀取和寫入的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 
+0

That's時,我說:「更新這些結構如果流程的變化」正是我的意思! 似乎這個代碼將任務變成一個毫不費力的任務! 非常感謝! – 2010-03-24 14:23:11

相關問題