Created
July 21, 2022 15:57
-
-
Save rob-murray/567b5e5e182fad6caf33b0ec1942bec7 to your computer and use it in GitHub Desktop.
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
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