Sha256: 5073c702d16880fa37b0a2c9305520e3ed6667c5838d29d4ab7871e503707ada

Contents?: true

Size: 993 Bytes

Versions: 6

Compression:

Stored size: 993 Bytes

Contents

# frozen_string_literal: true

module FFaker
  class UniqueUtils
    def initialize(generator, max_retries)
      @generator = generator
      @max_retries = max_retries
      @previous_results = Hash.new { |hash, key| hash[key] = Set.new }
    end

    def method_missing(name, *arguments)
      @generator.respond_to?(name) ? add_results_to_hash(name, *arguments) : super
    end

    def respond_to_missing?(method_name, include_private = false)
      super
    end

    RetryLimitExceeded = Class.new(StandardError)

    def clear
      @previous_results.clear
    end

    def self.clear
      ObjectSpace.each_object(self, &:clear)
    end

    private

    def add_results_to_hash(name, *arguments)
      @max_retries.times do
        result = @generator.send(name, *arguments)

        next if @previous_results[[name, arguments]].include?(result)

        @previous_results[[name, arguments]] << result
        return result
      end
      raise RetryLimitExceeded
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
ffaker-2.20.0 lib/ffaker/utils/unique_utils.rb
ffaker-2.19.0 lib/ffaker/utils/unique_utils.rb
ffaker-2.18.0 lib/ffaker/utils/unique_utils.rb
ffaker-2.17.0 lib/ffaker/utils/unique_utils.rb
ffaker-2.16.0 lib/ffaker/utils/unique_utils.rb
ffaker-2.15.0 lib/ffaker/utils/unique_utils.rb