Skip to content

Instantly share code, notes, and snippets.

@gouravtiwari
Forked from jcasimir/exporter.rb
Created October 24, 2013 07:36
Show Gist options
  • Save gouravtiwari/7132822 to your computer and use it in GitHub Desktop.
Save gouravtiwari/7132822 to your computer and use it in GitHub Desktop.
require 'csv'
class Exporter
DEFAULT_EXPORT_TABLES = [ Invoice, InvoiceItem, Item, Merchant, Transaction, User ]
DESTINATION_FOLDER = "tmp/"
def self.export_tables_to_csv(tables = DEFAULT_EXPORT_TABLES)
tables.each { |klass| export_table_to_csv(klass) }
end
def self.export_table_to_csv(klass)
output_file = CSV.open(filename_for_class(klass), "w")
output_file << klass.headers
klass.data.each{ |row| output_file << row }
output_file.close
end
def self.filename_for_class(klass)
DESTINATION_FOLDER + klass.to_s.underscore + '.csv'
end
end
class ActiveRecord::Base
def self.data
find(:all).map{ |i| i.data}
end
def self.headers
columns.map(&:name)
end
def data
self.class.headers.map { |column| self.send(column) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment