Skip to content

Instantly share code, notes, and snippets.

@avand
Created June 30, 2011 04:54
Show Gist options
  • Save avand/1055659 to your computer and use it in GitHub Desktop.
Save avand/1055659 to your computer and use it in GitHub Desktop.
CSV Model Exporter Task
namespace :csv do
task :export, :model, :attributes, :scope, :needs => :environment do |task, args|
raise ArgumentError, "Specify a model (e.g. rake sqoot:csv:export[User])" if args[:model].blank?
model = args[:model].constantize
models = model.send(args[:scope] || :all) # e.g. User.with_email || User.all
file_name = "#{args[:model].tableize}#{'_' + args[:scope] if args[:scope]}.csv" # e.g. users_with_email.csv
file = File.join(Rails.root, 'tmp', file_name)
columns = args[:attributes].try(:split, ',') || model.send(:new).attributes.keys
CSV.open(file, 'wb') do |csv|
csv << columns
models.each do |model_instance|
csv << columns.collect { |c| model_instance.send(c) }
end
end
# Not sure why, but it seems to be writing empty files to S3 (local seems OK)
"#{Rails.env}/csv/#{Time.now.strftime('%Y_%m_%d_%H:%M')}_#{file_name}".tap do |path|
S3Helper.copy(file, path)
puts "Saved to S3 at: #{path}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment