Sha256: 3ff2c58ab1166cc2ee36180446d63f8f2c033c1922a8bd4ac533418348e7f3d6

Contents?: true

Size: 1020 Bytes

Versions: 1

Compression:

Stored size: 1020 Bytes

Contents

# frozen_string_literal: true

module RandomPassword
  class Base
    LETTERS = [*'a'..'z', *'A'..'Z'].freeze
    DIGITS  = [*'0'..'9'].freeze
    SYMBOLS = %w(! " # $ % & ' ( ) * + , - . / \\ : ; ? @ [ ] ^ _ ` { | } ~).freeze

    def initialize(**options)
      update(options)
    end

    def generate
      password_letters.shuffle(random: Random.new).join[0...@length]
    end

    def update(**options)
      @length  = options[:length].to_i
      @digits  = options[:digits].to_i
      @symbols = options[:symbols].to_i
      self
    end

    private

    def password_letters
      passwords = []
      passwords.concat((0...@digits).map { random_digit })
      passwords.concat((0...@symbols).map { random_symbol })
      passwords.concat((0...(@length - @digits - @symbols)).map { random_letter })
    end

    def random_letter
      LETTERS[rand(LETTERS.size)]
    end

    def random_digit
      DIGITS[rand(DIGITS.size)]
    end

    def random_symbol
      SYMBOLS[rand(SYMBOLS.size)]
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
random_password-0.1.0 lib/random_password/base.rb