-
-
Save chad/1918269 to your computer and use it in GitHub Desktop.
Export ActiveRecord Tables to CSV
This file contains 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
require 'csv' | |
module Exporter | |
DEFAULT_EXPORT_TABLES = [ Invoice, InvoiceItem, Item, Merchant, Transaction, User ] | |
DESTINATION_FOLDER = "tmp/" | |
def self.included(klass) | |
klass.extend ClassLevelMethods | |
end | |
def self.export_tables_to_csv(tables = DEFAULT_EXPORT_TABLES) | |
tables.each do |klass| | |
klass.send(:include, self) | |
klass.export_table_to_csv | |
end | |
end | |
def data | |
self.class.column_names.map { |column| send(column) } | |
end | |
module ClassLevelMethods | |
def export_table_to_csv | |
CSV.open(filename_for_class, "w") do |output_file| | |
output_file << column_names | |
data.each{ |row| output_file << row } | |
end | |
end | |
def filename_for_class | |
[DESTINATION_FOLDER, to_s.pluralize.underscore, '.csv'].join | |
end | |
def data | |
all.map(&:data) | |
end | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(^_-) very true. This code could also work with other ORMs tho but granted using an ORM for that task seems totally overkill.