2010-03-24 57 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

相关问题