Sha256: e65facae20eb589c1a80231c0849ef5cf7a69f0333eac49425eaa14ef86598bb

Contents?: true

Size: 1.04 KB

Versions: 1

Compression:

Stored size: 1.04 KB

Contents

# frozen_string_literal: true

require "date"

module SwedishPIN
  # @private
  # @api private
  #
  # Generator for PINs.
  class Generator
    # Creates a new generator for a particular date.
    def initialize(random: Random)
      @random = random
    end

    # Generate a {Personnummer} with the given sequence number.
    def generate(date: random_date, sequence_number: random_sequence_number)
      # Handle someone explicitly passing `nil`.
      date ||= random_date
      sequence_number ||= random_sequence_number

      Personnummer.new(
        year: date.year,
        month: date.month,
        day: date.day,
        sequence_number: sequence_number,
        control_digit: control_digit(date, 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(date, sequence_number)
      padded = ("%03d" % sequence_number)
      SwedishPIN.luhn("#{date.strftime("%y%m%d")}#{padded}")
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
swedish-pin-2.0.0 lib/swedish_pin/generator.rb