Skip to content

Instantly share code, notes, and snippets.

@davidtingsu
Forked from robbyrussell/export.rake
Last active December 18, 2015 04:19
Show Gist options
  • Save davidtingsu/5724835 to your computer and use it in GitHub Desktop.
Save davidtingsu/5724835 to your computer and use it in GitHub Desktop.
#put in <project_directory>/lib/tasks
namespace :export do
desc "Export ActiveRecord model records to a CSV file. Pass model name: model=ModelName"
task :to_csv => :environment do
require 'exportable'
model_name = ENV['model']
open( "#{::Rails.root}" + '/log/export.pid', "w") do |file|
file << Process.pid
end
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
# put in <project_directory>/lib
require 'csv'
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
CSV.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