Skip to content

Instantly share code, notes, and snippets.

@stevehodges
Created May 21, 2019 02:26
Show Gist options
  • Save stevehodges/82bdf28e0fbbb71694b68f7cb2a5c0a9 to your computer and use it in GitHub Desktop.
Save stevehodges/82bdf28e0fbbb71694b68f7cb2a5c0a9 to your computer and use it in GitHub Desktop.
Faker::Company.name uniqueness
# Demonstration of why you should use Faker's .unique option when using
# Faker on attributes with uniqueness constraints
def first_collision_lazy
names={}
1_000.times do |a|
name = Faker::Company.name
return names.count if names[name]
names[name]=true
end
nil
end
def first_collision_uniq
names={}
1_000.times do |a|
name = Faker::Company.unique.name
return names.count if names[name]
names[name]=true
end
nil
end
def analyze(methodname)
results = 100.times.map{ send(methodname) }.compact
return "No duplicates over 100 runs" if results.empty?
"#{results.count} runs (out of 100) had duplicates, "\
"average first collision was on generated "\
"name ##{results.sum / results.count}"
end
analyze :first_collision_lazy
# => "100 runs (out of 100) had duplicates, average first collision was on generated name #164"
analyze :first_collision_uniq
# => No duplicates over 100 runs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment