Class: Faker::UniqueGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/helpers/unique_generator.rb

Constant Summary collapse

RetryLimitExceeded =
Class.new(StandardError)

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(generator, max_retries) ⇒ UniqueGenerator

Returns a new instance of UniqueGenerator


11
12
13
14
15
# File 'lib/helpers/unique_generator.rb', line 11

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

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *arguments) ⇒ Object

rubocop:disable Style/MethodMissingSuper

Raises:


18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/helpers/unique_generator.rb', line 18

def method_missing(name, *arguments)
  self.class.marked_unique.add(self)

  @max_retries.times do
    result = @generator.public_send(name, *arguments)

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

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

  raise RetryLimitExceeded, "Retry limit exceeded for #{name}"
end

Class Attribute Details

.marked_uniqueObject (readonly)

Returns the value of attribute marked_unique


8
9
10
# File 'lib/helpers/unique_generator.rb', line 8

def marked_unique
  @marked_unique
end

Class Method Details

.clearObject


44
45
46
47
# File 'lib/helpers/unique_generator.rb', line 44

def self.clear
  marked_unique.each(&:clear)
  marked_unique.clear
end

Instance Method Details

#clearObject


40
41
42
# File 'lib/helpers/unique_generator.rb', line 40

def clear
  @previous_results.clear
end

#exclude(name, arguments, values) ⇒ Object


49
50
51
52
53
54
# File 'lib/helpers/unique_generator.rb', line 49

def exclude(name, arguments, values)
  values ||= []
  values.each do |value|
    @previous_results[[name, arguments]] << value
  end
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

rubocop:enable Style/MethodMissingSuper

Returns:


34
35
36
# File 'lib/helpers/unique_generator.rb', line 34

def respond_to_missing?(method_name, include_private = false)
  method_name.to_s.start_with?('faker_') || super
end