Class: XKPassword::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/xkpassword/generator.rb

Overview

The Generator class which finds words based on the requirement and using the provided options to build a new random passowrd.

Constant Summary collapse

DEFAULTS =
{
  max_length: 8,
  min_length: 4,
  separator: '-',
  words: 4,
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeGenerator

Returns a new instance of Generator.



17
18
19
# File 'lib/xkpassword/generator.rb', line 17

def initialize
  @words = XKPassword::Words.new
end

Instance Attribute Details

#wordsXKPassword::Words (readonly)

A word database that gen provide you words for the length required

Returns:



7
8
9
# File 'lib/xkpassword/generator.rb', line 7

def words
  @words
end

Instance Method Details

#generate(options = nil) ⇒ String

Generates a password absed on the configuration provided.

Examples:

Populating the method with all options (current default)

options = {
  separator: ' ',
  words: 4,
  min_length: 4,
  max_length: 8
}

generator = XKPassword::Generator.new
generator.generate(options)

Parameters:

  • options (Hash) (defaults to: nil)

    The options to populate a generator

Options Hash (options):

  • :words (Integer)

    The number of words to include in the generated password

  • :separator (String)

    The separator symbol to use joining words used in password

  • :min_length (Integer)

    The minimum length of a word to be used in the process

  • :max_length (Integer)

    The maximum length of a word to be used in the process

Returns:

  • (String)

    The generated password



41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/xkpassword/generator.rb', line 41

def generate(options = nil)
  options ||= {}
  options = DEFAULTS.merge(options)
  length_vals = (options[:min_length]..options[:max_length]).to_a

  data = options[:words].times.map do
    word = words.random(length_vals.sample)
    upcase = [true, false].sample
    word = word.upcase if upcase
    word
  end
  
  data.join(options[:separator])
end