class Anonymise::DbFaker

Attributes

config[R]
db_args[R]

Public Class Methods

new(db_args, config, dry_run = false) click to toggle source
# File lib/anonymise/db_faker.rb, line 10
def initialize(db_args, config, dry_run = false)
  @db_args = db_args
  @config = config
  @dry_run = dry_run
end

Public Instance Methods

fake() click to toggle source
# File lib/anonymise/db_faker.rb, line 16
def fake
  config.each do |table, columns|
    if t_ables.include?(table)
      puts "Anonymising table #{table}".colorize(:green)
      columns.each do |column, type|
        if column_exists?(table, column)
          print("...#{fake_column(column, table, type)} records affected for column #{column}")
        else
          print "...column #{column} does not exist in #{table}_table".colorize(:red)
        end
        print "\n"
      end
      print "\n"
    else
      puts "Table #{table} does not exist on #{db_args[:db]}".colorize(:red)
    end
  end

  connection&.close
end
get_fake_for_type(type, origin_length) click to toggle source
# File lib/anonymise/db_faker.rb, line 37
def get_fake_for_type(type, origin_length)
  val = Faker::Alphanumeric.unique.alpha(number: origin_length)
  val = val.gsub(/[^a-z ]/, '')

  val = Faker::Company.name if type == 'company'
  val = Faker::Name.last_name if type == 'lastname'
  val = Faker::Name.first_name if type == 'firstname'
  if type == 'description'
    val = Faker::Lorem.paragraph_by_chars(number: 256, supplemental: false)
  end
  val = Faker::Internet.unique.email if type == 'email'
  val = Faker::Internet.unique.url if type == 'url'
  val = Faker::PhoneNumber.unique.cell if type == 'mobile'
  if type == 'number'
    val = Faker::Faker::Number.unique.number(digits: origin_length)
  end
  val.gsub(/'/, '')
end

Private Instance Methods

fake_column(column, table, type) click to toggle source
# File lib/anonymise/db_faker.rb, line 58
def fake_column(column, table, type)
  available_data = connection.exec("select * from #{table}")
  c_row_count = 0
  available_data.each do |record|
    c_row_count += 1
    origin_length = record[column]&.length || 6
    val = get_fake_for_type(type, origin_length)
    unless @dry_run
      connection.exec("UPDATE #{table} SET #{column}='#{val}' WHERE id='#{record['id']}'")
    end
  end
  c_row_count
end