require 'rake' require 'yaml' require 'rubygems/user_interaction' require 'fileutils' include Gem::UserInteraction

def list_of_tables_in_db

ActiveRecord::Base.connection.tables.to_a.find_all {|e| e != "schema_migrations" && e != "ar_internal_metadata" }

end

def capitalize1(obj)

if obj.include? "_"
  obj.camelize
else
  obj.capitalize
end

end

namespace :db do

task data_export_all: :environment do

  list_of_tables_in_db.each do |tableName|

          puts "Export #{tableName}"

          directory_name='backup_data'

          dir = File.dirname("#{Rails.root}/#{directory_name}/my.log")

          FileUtils.mkdir_p(dir) unless File.directory?(dir)

            # we assume that you get a file ready, the 'backup_data' directory has already been created and added in Rails.root
            filepath = File.join(Rails.root, 'backup_data', "#{tableName}"+'_exported.json')
            puts "- exporting #{tableName} into #{filepath}"

            # the key here is to use 'as_json', otherwise you get an ActiveRecord_Relation object, which extends
            # array, and works like in an array, but not for exporting
            #from a string I try to call a class instance with safe_constantize

            if capitalize1(tableName).singularize.safe_constantize != nil
              data = (capitalize1(tableName).singularize).safe_constantize.all.as_json

              # The pretty is nice so I can diff exports easily, if that's not important, JSON(users) will do
              File.open(filepath, 'w') do |f|
                f.write(JSON.pretty_generate(data))
              end

              puts "- dumped #{tableName.size} #{tableName}"
            end
  end

end

task data_import_all: :environment do

  list_of_tables_in_db.each do |tableName|

      puts "Importing all"

      filepath = File.join(Rails.root, 'backup_data', "#{tableName}"+'_exported.json')
      abort "Input file not found: #{filepath}" unless File.exist?(filepath)

      data = JSON.parse(File.read(filepath))

      data.each do |s|
        (capitalize1(tableName).singularize).safe_constantize.create(s)
      end

      puts "- imported #{tableName.size} #{tableName}"

  end

end

end