-
-
Save reborg/781702 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## | |
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## | |
# 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