Skip to content

Instantly share code, notes, and snippets.

@drush
Created February 2, 2024 20:40
Show Gist options
  • Save drush/5f9ebba50af3a60a6534c624f4fa4b4c to your computer and use it in GitHub Desktop.
Save drush/5f9ebba50af3a60a6534c624f4fa4b4c to your computer and use it in GitHub Desktop.
Rails Task to export a DB to mockdb.json compatible ith React-admin fakerest provider
# Utility for https://talysto.com/tech/groovestack applications
# Will export your current DB to a single JSON file that can be consumed directly
# by React-admin Fakerest adapter
# lib/tasks/db_export.rake
namespace :db do
desc 'Export all tables to a single JSON file, database-agnostic'
task export: :environment do
require 'json'
# Define an array of tables to exclude
exclude_tables = ['schema_migrations', 'ar_internal_metadata']
# Fetch all table names and exclude the ones specified in exclude_tables
tables = ActiveRecord::Base.connection.tables.reject { |table| exclude_tables.include?(table) }
database_export = tables.inject({}) do |hash, table|
data = ActiveRecord::Base.connection.exec_query("SELECT * FROM #{table}").to_a
# hash[table] = data
hash.merge(table => data)
end
json_data = JSON.pretty_generate(database_export)
# Define the file path within the db directory
file_path = Rails.root.join('db', 'mockdb.json')
FileUtils.mkdir_p(File.dirname(file_path))
File.write(file_path, json_data)
puts "Database export complete. Data saved to #{file_path}."
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment