Skip to content

Instantly share code, notes, and snippets.

@reborg
Forked from adamwiggins/export_via_sequel.rb
Created January 16, 2011 11:15
Show Gist options
  • Save reborg/781702 to your computer and use it in GitHub Desktop.
Save reborg/781702 to your computer and use it in GitHub Desktop.
##
# Ideas for this CSV export comes from:
# - http://dominikgrabiec.com/111-simple-dataset-exportimport-for-rails/
#
namespace :teamly do
namespace :export do
desc 'CSV Export of the relevant user data'
task :users => :environment do
excludes = ['crypted_password','password_salt','persistence_token','single_access_token','perishable_token','ancestry','time_zone','hide_announcement_time','reminder_hour','reminder_min']
export_csv_file_for_table_with_exclusions('users', excludes)
end
desc 'CSV Export of the relevant account data'
task :accounts => :environment do
export_csv_file_for_table_with_exclusions('accounts')
end
end
def export_csv_file_for_table_with_exclusions(table, excludes = [])
require "fastercsv"
require "fileutils"
ActiveRecord::Base.establish_connection
database = ActiveRecord::Base.connection
FasterCSV.open(File.join(File.dirname(__FILE__), "/../../#{table}.csv"), "w") do |csv|
csv << includes = database.columns(table).map(&:name) - excludes
database.select_rows("select #{includes.join(',')} from #{table}").each { |row| csv << row }
end
end
end
##
# More info at: http://adam.heroku.com/past/2009/3/30/export_to_csv/
# Use as:
# DATABASE_URL=sqlite://db/development.sqlite3 rake export table=users > users.csv
task :export do
require 'sequel'
require 'fastercsv'
db = Sequel.connect(ENV['DATABASE_URL'])
table_name = ENV['table'].to_sym
table = db[table_name]
fields = table.first.keys
csv = FasterCSV.generate do |csv|
csv << fields
table.all.each do |record|
csv << fields.map { |f| record[f] }
end
end
puts csv
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment