Skip to content

Instantly share code, notes, and snippets.

@bcavileer
Created March 16, 2016 14:25
Show Gist options
  • Select an option

  • Save bcavileer/b9801f2951ec7f188e01 to your computer and use it in GitHub Desktop.

Select an option

Save bcavileer/b9801f2951ec7f188e01 to your computer and use it in GitHub Desktop.
Dump Rails 2.3 Ruby 1.8 ActiveRecord Objects to CSV
require 'csv'
class ActiveRecord::Base
class << self
def dump_all
descendants.each(&:to_csv)
nil
end
def to_csv(filename=csv_export_filename)
CSV.generate(filename) do |csv|
csv << column_names
with_exclusive_scope do
find_in_batches do |objs|
objs.each do |obj|
csv << column_names.map { |attr| obj.send(attr) }
end
end
end
end
end
def csv_export_filename
"#{class_name.underscore}-#{Date.current.to_s}.csv"
end
def descendants
ObjectSpace.each_object(Class).select { |klass| klass < self }
end
end
end
ActiveRecord::Base.dump_all
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment