From: Daniel Sheppard Date: 2007-11-01T11:33:36+09:00 Subject: Re: Extending ActiveRecord for csv export... a better way? > As a new Ruby user (JRuby, actually), I've picked up this > language with > a very specific purpose: to export data from a JDBC database into flat > files. I've figured out how to get the data out of the DB and into a > file (using ActiveRecord-JDBC), but it requires a bit too much > configuration. My first stab implementation requires me to define an > activerecord class for each table I want to export, and to define a > method all_columns in each class > that lays out the columns in the correct order. I've also setup a > module (CSVable) that extends ActiveRecord so I can call the export > function directly on each class. Here is the code: require 'fastercsv' def to_csv(records, filename=nil, columns=nil) filename ||= "#{records.first.class.table_name}.dat" columns ||= records.first.class.columns.map {|x| x.name } FasterCSV.open(filename, 'w') do |csv| records.each do |record| csv << columns.map {|column| record.attributes[column] } end end end class UsrUserAccount < ActiveRecord::Base set_table_name "USR.USER_ACCOUNT" end to_csv(UsrUserAccount.find(:all))