Sha256: e12053cf4a21e5abced68b6a3c51d26fde8a7f76fdc07f0b89ffa2e1d7de4c28

Contents?: true

Size: 1011 Bytes

Versions: 2

Compression:

Stored size: 1011 Bytes

Contents

# frozen_string_literal: true

require "date"

module SwedishPIN
  # @private
  # @api private
  #
  # Generator for PINs.
  class Generator
    # The date all generated PINs will be based on.
    attr_reader :date

    # Creates a new generator for a particular date.
    def initialize(date)
      @date = date || random_date
    end

    # Generate a {Personnummer} with the given sequence number.
    def generate(sequence_number)
      sequence_number ||= random_sequence_number
      Personnummer.new(
        year: date.year,
        month: date.month,
        day: date.day,
        sequence_number: sequence_number,
        control_digit: control_digit(sequence_number)
      )
    end

    private

    def random_date
      Date.today - Random.rand(0..(110 * 365))
    end

    def random_sequence_number
      Random.rand(0..999)
    end

    def control_digit(sequence_number)
      padded = ("%03d" % sequence_number)
      SwedishPIN.luhn("#{date.strftime("%y%m%d")}#{padded}")
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
swedish-pin-1.1.0 lib/swedish_pin/generator.rb
swedish-pin-1.0.0 lib/swedish_pin/generator.rb