Wednesday, March 29, 2023

Mask Data and Export

Add both faker and dumped_railers gems to your Gemfile:

 gem 'faker'

gem 'dumped_railers', require: false


Run bundle install to install the gems.

Create a custom preprocessor to use fake values for first_name, last_name, and email:


class FakeUserDataPreprocessor
  def call(model, attrs)
    if model == User
      attrs['first_name'] = Faker::Name.first_name
      attrs['last_name'] = Faker::Name.last_name
      attrs['email'] = Faker::Internet.email
    end
  end
end

Use the dumped_railers gem to export the users table with the custom preprocessor:

require 'dumped_railers'
require 'fake_user_data_preprocessor'

# Replace 'User.limit(10)' with a more specific query if needed.
DumpedRailers.dump!(User.limit(10), base_dir: 'tmp/fixtures/', preprocessors: [FakeUserDataPreprocessor.new])

This will create a fixture file in the tmp/fixtures/ directory with the User data, including the fake values for first_name, last_name, and email.

To import the data, use the following command:

DumpedRailers.import!('tmp/fixtures')

Please note that the FakeUserDataPreprocessor will replace the original first_name, last_name, and email values with fake data in the exported fixture file. If you want to keep the original data, you may need to create a backup before running this process.