Sha256: 425f6dd839efdc5e59331e8b05fbfe4ac8f0096c64b7a18ea32fe01be45ab187

Contents?: true

Size: 1008 Bytes

Versions: 9

Compression:

Stored size: 1008 Bytes

Contents

# frozen_string_literal: true

require 'set'

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

9 entries across 9 versions & 1 rubygems

Version Path
ffaker-2.14.0 lib/ffaker/utils/unique_utils.rb
ffaker-2.13.0 lib/ffaker/utils/unique_utils.rb
ffaker-2.12.0 lib/ffaker/utils/unique_utils.rb
ffaker-2.11.0 lib/ffaker/utils/unique_utils.rb
ffaker-2.10.0 lib/ffaker/utils/unique_utils.rb
ffaker-2.9.0 lib/ffaker/utils/unique_utils.rb
ffaker-2.8.1 lib/ffaker/utils/unique_utils.rb
ffaker-2.8.0 lib/ffaker/utils/unique_utils.rb
ffaker-2.7.0 lib/ffaker/utils/unique_utils.rb