Skip to content

Instantly share code, notes, and snippets.

@rob-murray
Created July 21, 2022 15:57
Show Gist options
  • Save rob-murray/567b5e5e182fad6caf33b0ec1942bec7 to your computer and use it in GitHub Desktop.
Save rob-murray/567b5e5e182fad6caf33b0ec1942bec7 to your computer and use it in GitHub Desktop.
namespace :export do
desc <<-DESC.strip_heredoc
Export tables listed as YAML
Usage: `rails export:tables TABLES=users,posts,comments`
DESC
task tables: :environment do
models = ENV["TABLES"].split(",").map do |name|
name.to_s.classify.constantize
rescue NameError
nil
end.compact
raise ArgumentError, "Please specify tables to export" if models.empty?
models.each do |model|
next unless model.ancestors.include?(ActiveRecord::Base)
file_name = "#{Rails.root}/spec/fixtures/#{model.table_name}.yml"
Rails.logger.info "Exporting #{model} to file='#{file_name}'..."
File.open(file_name, 'w') do |f|
model.order(id: :asc).all.each_with_index do |record, i|
attrs = record.attributes.except('created_at', 'updated_at')
attrs.delete_if { |_,v| v.blank? }
fixture = { [model.table_name, '_', i.to_s].join => attrs }
f << fixture.to_yaml.gsub(/^--- \n/, '') + "\n"
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment