Skip to content

Instantly share code, notes, and snippets.

@thdaraujo
Last active February 21, 2024 17:20
Show Gist options
  • Save thdaraujo/36cf8f414a018ee63e53901281480c74 to your computer and use it in GitHub Desktop.
Save thdaraujo/36cf8f414a018ee63e53901281480c74 to your computer and use it in GitHub Desktop.
# 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