Skip to content

Commit

Permalink
Extend lib/tasks/extract_fixtures.rake
Browse files Browse the repository at this point in the history
  • Loading branch information
sanak committed Dec 7, 2024
1 parent 2f817fc commit e3e7b4e
Showing 1 changed file with 40 additions and 8 deletions.
48 changes: 40 additions & 8 deletions lib/tasks/extract_fixtures.rake
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,51 @@
desc 'Create YAML test fixtures from data in an existing database.
Defaults to development database. Set RAILS_ENV to override.'

module Psych
module Visitors
class YAMLTree
# Override default format
# https://github.com/ruby/ruby/blob/v3_3_6/ext/psych/lib/psych/visitors/yaml_tree.rb#L484-L490
def format_time time, utc = time.utc?
if utc
time.strftime("%Y-%m-%d %H:%M:%S")
else
time.strftime("%Y-%m-%d %H:%M:%S %:z")
end
end
end
end
end

task :extract_fixtures => :environment do
sql = "SELECT * FROM %s"
skip_tables = ["schema_info"]
dir = ENV['DIR'] || 'tmp/fixtures'
omit_default_or_nil = ActiveRecord::Type::Boolean.new.cast(ENV.fetch('OMIT_DEFAULT_OR_NIL', 'false'))

FileUtils.mkdir_p(dir)

skip_tables = ["schema_migrations", "ar_internal_metadata"]
ActiveRecord::Base.establish_connection
(ActiveRecord::Base.connection.tables - skip_tables).each do |table_name|
i = "000"
File.open("#{Rails.root}/#{table_name}.yml", 'w' ) do |file|
data = ActiveRecord::Base.connection.select_all(sql % table_name)
File.open(Rails.root.join(dir, "#{table_name}.yml"), 'w') do |file|
columns = ActiveRecord::Base.connection.columns(table_name)
column_names = columns.map(&:name)
order_columns = column_names.include?('id') ? 'id' : column_names.join(', ')
sql = "SELECT * FROM #{table_name} ORDER BY #{order_columns}"
data = ActiveRecord::Base.connection.select_all(sql)
file.write data.inject({}) { |hash, record|
# cast extracted values
ActiveRecord::Base.connection.columns(table_name).each { |col|
record[col.name] = col.type_cast(record[col.name]) if record[col.name]
}
# omit default or nil values or format time values
columns.each do |col|
if omit_default_or_nil &&
((!col.default.nil? && !record[col.name].nil? && record[col.name].to_s == col.default) ||
col.default.nil? && record[col.name].nil?)
record.delete(col.name)
next
elsif col.type == :datetime && record[col.name].present?
time = record[col.name].is_a?(String) ? Time.zone.parse(record[col.name]) : record[col.name]
record[col.name] = time
end
end
hash["#{table_name}_#{i.succ!}"] = record
hash
}.to_yaml
Expand Down

0 comments on commit e3e7b4e

Please sign in to comment.