将ActiveRecord对象导出到PORO中

时间:2010-03-24 11:40:23

标签: ruby-on-rails ruby object export

我正在开发一个“脚本生成器”来自动化某些工作流程。 它有一个在服务器上运行的Rails应用程序,它存储制作脚本所需的所有数据,并在流程结束时自己生成脚本。

我遇到的问题是如何将数据从ActiveRecord格式导出到Plain Old Ruby Objects(PORO),这样我就可以在我的脚本中处理它们而没有数据库支持和纯ruby实现。

我考虑过YAML,CSV或类似的东西来导出数据,但如果流程发生变化,更新这些结构将是一个痛苦的过程。有更简单的方法吗?

泰!

1 个答案:

答案 0 :(得分:2)

通过“在进程发生更改时更新这些结构”,是指更改在数据库中的字段发生更改时读取和写入CSV或YAML数据的代码?

以下代码在CSV中写入和读取任何AR对象(需要FasterCSV gem):

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