Created
March 16, 2016 14:25
-
-
Save bcavileer/b9801f2951ec7f188e01 to your computer and use it in GitHub Desktop.
Dump Rails 2.3 Ruby 1.8 ActiveRecord Objects to CSV
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
| 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