Last active
February 21, 2024 17:20
-
-
Save thdaraujo/36cf8f414a018ee63e53901281480c74 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Example of how to create a lazy generator for Faker that | |
# can exclude certain values. | |
# | |
# How to run: | |
# ruby faker_excluding_generator.rb | |
# | |
require "faker" | |
require "test/unit" | |
# build a lazy generator | |
def generator(excluding: Set[], &block) | |
Enumerator.new do |yielder| | |
loop do | |
e = block.call | |
next if excluding.include?(e) | |
yielder << e | |
end | |
end | |
end | |
# or a lambda | |
def lambda_generator | |
lambda do |excluding, &block| | |
100.times do | |
result = block.call | |
next if excluding.include?(result) | |
return result | |
end | |
end | |
end | |
class ExclusiveTest < Test::Unit::TestCase | |
def test_generator | |
address_generator = generator(excluding: Set["US"]) do | |
Faker::Address.country_code | |
end | |
1000.times do | |
address = address_generator.next | |
assert address.is_a? String | |
assert_not_equal address, "US" | |
end | |
end | |
def test_lambda_generator | |
1000.times do | |
address = lambda_generator.call(Set["US"]) do | |
Faker::Address.country_code | |
end | |
assert address.is_a? String | |
assert_not_equal address, "US" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment