Skip to content

Instantly share code, notes, and snippets.

@jcasimir
Forked from chad/exporter.rb
Created February 26, 2012 20:09
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save jcasimir/1918759 to your computer and use it in GitHub Desktop.
Save jcasimir/1918759 to your computer and use it in GitHub Desktop.
Export ActiveRecord Tables to CSV
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 &:export_table_to_csv
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
class ActiveRecord::Base
include Exporter
end
@jcasimir
Copy link
Author

Tested, just needed two minor fixes.

The Module having three jobs here (hosting class methods, defining instance methods for the including class, defining class methods for the including class) is kind of awesome and, at the same time, makes me feel a bit uncomfortable. Is that unreasonable?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment