Skip to content

Instantly share code, notes, and snippets.

@robbyrussell
Created August 31, 2008 00:02
Show Gist options
  • Save robbyrussell/8154 to your computer and use it in GitHub Desktop.
Save robbyrussell/8154 to your computer and use it in GitHub Desktop.
rake task and library extension for ActiveRecord to export a model's records to a CSV file
namespace :export do
desc "Export ActiveRecord model records to a CSV file. Pass model name: model=ModelName"
task :to_csv => :environment do
require 'exportable'
open(RAILS_ROOT + '/log/export.pid', "w") do |file|
file << Process.pid
end
model_name = ENV['model']
File.open( RAILS_ROOT + "/tmp/#{model_name}.csv", "w" ) { |f|
f << model_name.constantize.send( :to_csv )
}
File.unlink(RAILS_ROOT + '/log/export.pid')
end
end
#
# inspired by
# http://www.brynary.com/2007/4/28/export-activerecords-to-csv
#
require "fastercsv"
class ActiveRecord::Base
def self.to_csv(*args)
find(:all).to_csv(*args)
end
def export_columns(format = nil)
['id'] + self.class.content_columns.map(&:name)
end
def to_row(format = nil)
export_columns(format).map { |c| self.send(c) }
end
end
class Array
def to_csv(options = {})
if all? { |e| e.respond_to?(:to_row) }
header_row = first.export_columns(options[:format]).to_csv
content_rows = map { |e| e.to_row(options[:format]) }.map(&:to_csv)
([header_row] + content_rows).join
else
FasterCSV.generate_line(self, options)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment