Skip to content

Commit

Permalink
Add "exclude" method to UniqueGenerator (faker-ruby#1307)
Browse files Browse the repository at this point in the history
  • Loading branch information
mtancoigne authored and stympy committed Jul 14, 2018
1 parent 1da27b5 commit 70823a0
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,18 @@ Faker::Name.unique.clear # Clears used values for Faker::Name
Faker::UniqueGenerator.clear # Clears used values for all generators
```

You also can give some already used values to the unique generator if you have
collisions with the generated data (i.e: using FactoryBot with random and
manually set values).

```ruby
# Usage:
# Faker::<generator>.unique.exclude(method, arguments, list)

# Add 'azerty' and 'wxcvbn' to the string generator with 6 char length
Faker::Lorem.unique.exclude :string, [6], %w[azerty wxcvbn]
```

### Deterministic Random

Faker supports seeding of its pseudo-random number generator (PRNG) to provide deterministic output of repeated method calls.
Expand Down
7 changes: 7 additions & 0 deletions lib/helpers/unique_generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,5 +36,12 @@ def clear
def self.clear
ObjectSpace.each_object(self, &:clear)
end

def exclude(name, arguments, values)
values ||= []
values.each do |value|
@previous_results[[name, arguments]] << value
end
end
end
end
6 changes: 6 additions & 0 deletions test/test_faker_lorem.rb
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,10 @@ def test_paragraph_char_count
paragraph = @tester.paragraph_by_chars(256)
assert(paragraph.length == 256)
end

def test_unique_with_already_set_values
values = ('a'..'z').to_a + ('0'..'9').to_a
@tester.unique.exclude(:character, [], values)
assert_raise(Faker::UniqueGenerator::RetryLimitExceeded) { @tester.unique.character }
end
end

0 comments on commit 70823a0

Please sign in to comment.