Sha256: c35080fc9d80eee0242a86eecc1723c642374f46dfeeb3baeb3d87f6ab51a7aa

Contents?: true

Size: 1.76 KB

Versions: 2

Compression:

Stored size: 1.76 KB

Contents

# frozen_string_literal: true

module DirtySeed
  module Assigners
    # Helps with faker values
    module FakerHelper
      MAX_RETRIES = 1_000
      private_constant :MAX_RETRIES

      # Returns a rabdom value matching the requirements
      # @param generator [Symbol] faker generator
      # @param method [Symbol] faker method
      # @param options [Hash] options used by faker
      # @return [Object]
      # @example
      #   faker_value(generator: :Internet, method: :email, options: { domain: 'example' })
      #     #=> "alice@example.name"
      # @note Faker raises a RetryLimitExceeded if it reaches MAX_RETRIES (with a unique generator)
      #   In this case return nil since it appears not to be possible to return a new unique value
      def faker_value(generator:, method:, options: nil)
        params = options ? [method, options] : [method]
        faker_generator(generator).public_send(*params)
      rescue Faker::UniqueGenerator::RetryLimitExceeded
        nil
      end

      private

      # Returns a faker generator
      # @param generator [Symbol] fake generator
      # @return [Class, Faker::UniqueGenerator] a faker class or a faker unique generator
      # @example
      #   Faker::Lorem
      #   Faker::UniqueGenerator.new(Faker::Lorem)
      def faker_generator(generator)
        @faker_generator ||=
          if unique?
            Faker::UniqueGenerator.new("::Faker::#{generator}".constantize, MAX_RETRIES)
          else
            "::Faker::#{generator}".constantize
          end
      end

      # Should the value be unique?
      # @return [Boolean]
      def unique?
        @unique ||=
          validators&.any? do |validator|
            validator.is_a? ActiveRecord::Validations::UniquenessValidator
          end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
dirty_seed-0.2.1 lib/dirty_seed/assigners/helpers/faker_helper.rb
dirty_seed-0.2.0 lib/dirty_seed/assigners/helpers/faker_helper.rb