Last active
March 15, 2016 23:58
-
-
Save ddd1600/5138f009d8d38533a343 to your computer and use it in GitHub Desktop.
patch that adds two methods, dump_json and read_json to any active record model as class methods. Very useful for restoring databases onto production servers, for example.
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
class ActiveRecord::Base | |
def self.dump_json(sql="") | |
records = sql.blank? ? all : where(sql) | |
`touch #{self}_backup.json` | |
File.open(File.join(Rails.root, "#{self}_backup.json"), 'w') do |f| | |
f.write(records.to_json) | |
end | |
end | |
def self.read_json(safe_mode=true) | |
silence do | |
ids = safe_mode ? all.map(&:id) : [] | |
ary = JSON.parse(File.read(File.join(Rails.root, "#{self}_backup.json"))) | |
rcount = ary.count | |
ary.each_with_index do |ar_hash, i| | |
next if ids.include?(ar_hash["id"]) | |
print "\r#{i}/#{rcount}" | |
r = new | |
column_names.each do |name| | |
r.send("#{name}=".to_sym, ar_hash[name]) | |
end | |
r.save | |
end# of records array | |
puts "\nrecords upload complete." | |
end# of silence | |
end# of method | |
def self.dump_schema | |
`touch #{self}_schema_backup.json` | |
File.open("#{self}_schema.json", "w") {|f| f.write(columns.map{|c| [c.name, c.type]}.to_json) } | |
end# | |
end#of class |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment