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

Raises:


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

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


46
47
48
49
# File 'lib/helpers/unique_generator.rb', line 46

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

Instance Method Details

#clearObject


42
43
44
# File 'lib/helpers/unique_generator.rb', line 42

def clear
  @previous_results.clear
end

#exclude(name, arguments, values) ⇒ Object


51
52
53
54
55
56
# File 'lib/helpers/unique_generator.rb', line 51

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

Returns:


36
37
38
# File 'lib/helpers/unique_generator.rb', line 36

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